天天看點

Android常用UI

詳細介紹清單視圖(ListView)、單選(RadioGroup)、多選(CheckBox)、下拉清單(Spinner)、菜單(Menu)、内容提示文本框(AutoCompleteTextView)、手勢識别(GestureOverlayView)、網頁視圖(WebView)。

1.清單視圖(ListView)

Android常用UI

XML配置

     在主界面中配置<ListView>标簽

     在res/layout/檔案夾下建立一個新的xml檔案指定每個條目的布局

Java代碼建構ListView

     擷取ListView對象

     設定一個Adapter

          用擴充卡封裝有兩種方式:

             1.SimpleAdapter:以List<Map<String,?>>形式封裝資料

             2.SimpleCursorAdapter:以Cursor對象封裝資料,Cursor中需要有“_id”一列

添加OnItemClickListener

     調用ListView的getItemAtPosition(int)方法可以擷取封裝資料的容器

     如果傳入的是SimpleAdapter,擷取到的就是一個Map<String,?>

     如果傳入的是SimpleCursorAdapter,獲得到的就是一個Cursor,并且Cursor以指向選中的一條記錄

 示例:

用SimpleAdapter進行資料綁定

public class MainActivity extends Activity {
    private PersonService service;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        service = new PersonService(this);
        ListView listView = (ListView) this.findViewById(R.id.listView);
        
        //擷取到集合資料
        List<Person> persons = service.getScrollData(0, 10);
        List<HashMap<String, Object>> data = new ArrayList<HashMap<String,Object>>();
        for(Person person : persons){
        	HashMap<String, Object> item = new HashMap<String, Object>();
        	item.put("id", person.getId());
        	item.put("name", person.getName());
        	item.put("phone", person.getPhone());
        	item.put("amount", person.getAmount());
        	data.add(item);
        }
       //建立SimpleAdapter擴充卡将資料綁定到item顯示控件上
       SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, 
        		new String[]{"name", "phone", "amount"}, new int[]{R.id.name, R.id.phone, R.id.amount});
       //實作清單的顯示
       listView.setAdapter(adapter);
       //條目點選事件
       listView.setOnItemClickListener(new ItemClickListener());
    }
       //擷取點選事件    
    private final class ItemClickListener implements OnItemClickListener{

		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			ListView listView = (ListView) parent;
			HashMap<String, Object> data = (HashMap<String, Object>) listView.getItemAtPosition(position);
			String personid = data.get("id").toString();
			Toast.makeText(getApplicationContext(), personid, 1).show();
		}
    }
}
           

 用SimpleCursorAdapter進行資料綁定

public class MainActivity extends Activity {
    private PersonService service;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        service = new PersonService(this);
        ListView listView = (ListView) this.findViewById(R.id.listView);
        //擷取遊标
        Cursor cursor = service.getCursorScrollData(0, 10);
        //建立SimpleCursorAdapter擴充卡将資料綁定到item顯示控件上
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, 
        		new String[]{"name", "phone", "amount"}, new int[]{R.id.name, R.id.phone, R.id.amount});
        listView.setAdapter(adapter);
        //條目點選事件
        listView.setOnItemClickListener(new ItemClickListener());
    }
    
    private final class ItemClickListener implements OnItemClickListener{

		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			ListView listView = (ListView) parent;
			Cursor cursor = (Cursor) listView.getItemAtPosition(position);
			String personid = String.valueOf(cursor.getInt(cursor.getColumnIndex("_id")));
			Toast.makeText(getApplicationContext(), personid, 1).show();
		}
    }
}

           

2.單選(RadioGroup)

Android常用UI

定義<RadioGroup> 

在<RadioGroup>中定義<RadioButton>和<Button>

處理Button點選事件

根據ID擷取RadioGroup對象,調用其getCheckedRadioButtonId()方法可以擷取其中被選中的RadioGroup的ID

 main.xml:

<RadioGroup
      android:id="@+id/radioGroup"
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal"
      >
    	<RadioButton
    	  android:id="@+id/java"
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content" 
    	  android:text="Java"
    	  android:layout_weight="1"
    	/>  
    	<RadioButton
    	  android:id="@+id/net"
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content" 
    	  android:text=".NET"
    	  android:layout_weight="1"
    	/>  
    	<RadioButton
    	  android:id="@+id/php"
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content" 
    	  android:text="PHP"
    	  android:layout_weight="1"
    	/>  
         <Button
    	  android:id="@+id/php"
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content" 
    	  android:text="确定"
    	  android:onClick="submitRadio"
    	  android:layout_weight="1"
    	 />
    </RadioGroup>
           

MainActivity:

public void submitRadio(View view){
    	//擷取選中按鈕的ID
    	int id =radioGroup.getCheckedRadioButtonId();
    	RadioButton radioButton=(RadioButton)findViewById(id);
    	Toast.makeText(this,radioButton.getText(), 0).show();
    }
           

3.多選(CheckBox)

Android常用UI

定義若幹<CheckBox>和一個<Button>

處理Button的點選事件

根據findViewById擷取每個CheckBox,調用其isChecked()方法判斷是否被選中

<LinearLayout
    	android:layout_width="fill_parent"
    	android:layout_height="wrap_content"
    	>
    	<CheckBox
    	  android:id="@+id/javaCheckBox"
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content" 
    	  android:text="Java"
    	  android:layout_weight="1"
    	/>  
    	<CheckBox
    	  android:id="@+id/netCheckBox"
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content" 
    	  android:text=".NET"
    	  android:layout_weight="1"
    	/>  
    	<CheckBox
    	  android:id="@+id/phpCheckBox"
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content" 
    	  android:text="PHP"
    	  android:layout_weight="1"
    	/>  
         <Button
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content" 
    	  android:text="确定"
    	  android:onClick="submitCheckBox"
    	  android:layout_weight="1"
    	 />
   </LinearLayout>
           

4.下拉清單(Spinner)

定義<Spinner>标簽

建立一個擴充卡

擷取Spinner标簽,調用setAdapter(SpinnerAdapter adapter)方法設定一個擴充卡

調用setOnItemSelectedListener(OnItemSelectedListener listener)方法設定監聽器監聽選中事件

使用字元串建構擴充卡

Android常用UI
public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		spinner = (Spinner) findViewById(R.id.spinner);
		generateSpinner();
	}

	private void generateSpinner() {
		//android.R.layout.simple_spinner_item下拉清單的樣式
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adapter.add("Java");
		adapter.add(".NET");
		adapter.add("PHP");
		spinner.setAdapter(adapter);
		//監聽器
		spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				String selection=(String)parent.getItemAtPosition(position);
				Toast.makeText(getApplicationContext(), selection, 0).show();
			}
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}
           

使用JavaBean建構擴充卡

Android常用UI
private void generateSpinnerByJavaBean() {
		ArrayAdapter<User> adapter = new ArrayAdapter<User>(this, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adapter.add(new User(1,"aaa","[email protected]"));
		adapter.add(new User(2,"bbb","[email protected]"));
		adapter.add(new User(3,"ccc","[email protected]"));
		spinner.setAdapter(adapter);
		//監聽器
		spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				User user=(User)parent.getItemAtPosition(position);
				Toast.makeText(getApplicationContext(), user.toString(), 0).show();
			}
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}
           

使用資源檔案建構擴充卡

支援國際化

資源檔案:

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string-array name="items">
		<item>Java</item>
		<item>.NET</item>
		<item>PHP</item>
	</string-array>
</resources>
           

MainActivity

private void generateSpinnerByResource() {
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.items, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				CharSequence selection=(CharSequence)parent.getItemAtPosition(position);
				Toast.makeText(getApplicationContext(), selection, 0).show();
			}
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}
           

自定義擴充卡樣式

Android常用UI

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.custom, R.id.content);

R.layout.custom 布局檔案ID

R.id.content 哪一個元件用來顯示文本

自定義布局檔案:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  >
  <ImageView
  	  android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:src="@android:drawable/btn_radio"
  />
  <TextView
  	  android:id="@+id/content"
  	  android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginLeft="30dp"
      android:textColor="#FFFF0000"
      android:textSize="30sp"
  />
</LinearLayout>
           

activity:

private void generateSpinnerByResource() {
		ArrayAdapter<String> adapter =new ArrayAdapter<String>(this,R.layout.item,R.id.content);
		adapter.add("java");
		adapter.add(".NET");
		adapter.add("php");
		spinner.setAdapter(adapter);
	}
           

5.菜單(Menu)

Android常用UI
Android常用UI

添加菜單項

1.重寫Actvity的onCreateOptionsMenu(Menu menu)方法

2.添加菜單項

     調用方法中參數menu的add(CharSequence title) 方法

3.添加子菜單

    調用menu對象的addSubMenu(final CharSequence title)

    該方法傳回一個SubMenu對象

4.添加子菜單的菜單項

   調用SubMenu對象的add(CharSequence title) 方法

處理菜單點選事件

重寫Activity的onOptionsItemSelected(MenuItem item) 方法

     參數item即為被選中的菜單項

/*
	 * 點選菜單按鈕時會調用這個方法
	 * 支援子菜單,子菜單中不能再建立子菜單
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE,0,1,"增加1");
		menu.add(Menu.NONE,1,0,"增加2");
		menu.add("修改");
		menu.add("删除"); 
		//建立子菜單
		SubMenu subMenu=menu.addSubMenu("查詢");
		subMenu.add("按id查詢");
		subMenu.add("按名字查詢");
		subMenu.add("按郵箱查詢");
		return super.onCreateOptionsMenu(menu);
	}
	
	/*
	 * 點選菜單項會執行這個方法
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		Toast.makeText(this, item.getTitle(), 0).show();
		return super.onOptionsItemSelected(item);
	}
           

6.手勢識别(GestureOverlayView)

建立手勢庫

Android常用UI

導入SDK中的工程

   android-sdk-windows\samples\android-8\GestureBuilder

   這個工程不能直接導入,需要添加三個配置檔案:.classpath、.project、default.properties

将工程部署到手機中,建立手勢庫

   手勢庫會存儲在手機SD卡的根目錄

使用手勢識别

Android常用UI
Android常用UI

XML配置:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<android.gesture.GestureOverlayView
		android:id="@+id/gov"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent"
		android:gestureStrokeType="multiple"
	    >
	    <ImageView
	    	android:id="@+id/img"
	    	android:layout_width="wrap_content" 
	    	android:layout_height="wrap_content" 
	    	/>
	</android.gesture.GestureOverlayView>
</LinearLayout>
           

Java代碼:

public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		gov = (GestureOverlayView) findViewById(R.id.gov);
		img=(ImageView) findViewById(R.id.img);
		//擷取到手勢庫,并加載
		library = GestureLibraries.fromRawResource(this, R.raw.gestures);
		library.load();
		gov.addOnGesturePerformedListener(new MyListener());
	}
	private final class MyListener implements OnGesturePerformedListener {
		public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
			//手勢庫來比對手勢
			ArrayList<Prediction> list = library.recognize(gesture);
			
			//查詢手勢庫比對的分值并列印
			for(Prediction p:list){
				System.out.println(p.name+":"+p.score);
			}
			
			//擷取比對度最高的選項
			Prediction p =list.get(0);
			
			//如果比對值小于3則不能識别
			if(p.score<3){
				Toast.makeText(getApplicationContext(), "手勢不能識别", 0).show();
			}else if("true".equals(p.name)){
				//執行的内容
			}else if("o".equals(p.name)){
				//執行的内容
			}else if("x".equals(p.name)){
				//執行的内容
			}
		}
	}
           

7.網頁視圖(WebView)

WebView(網絡視圖)能加載顯示網頁,它使用了WebKit渲染引擎加載顯示網頁,WebKit是android手機中内置了一款高性能核心浏覽器。

Android常用UI

XML配置:

<WebView
		android:id="@+id/webView"
		android:layout_width="fill_parent" 
	    android:layout_height="fill_parent"
		/>
           

java代碼:

WebView webView = (WebView) findViewById(R.id.webView);
		// 或取内容
		String url = editText.getText().toString();
		// 設定是否可縮放
		webView.getSettings().setBuiltInZoomControls(true);
		// 設定是否支援腳本
		webView.getSettings().setJavaScriptEnabled(true);
		// 設定用戶端(谷歌Chrome用戶端)
		webView.setWebChromeClient(new WebChromeClient());
		// 加載頁面
		webView.loadUrl(url);
           

8.内容提示文本框(AutoCompleteTextView)

單次提示

Android常用UI

   XML檔案:

<AutoCompleteTextView
    	android:id="@+id/actv"
    	android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:completionThreshold="1"
    	/>
           

   Java代碼:

private void generateActv() {
		AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.actv);
		String[] items = { "tom", "tony", "terry", "付東", "付榮", "付貴" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, items);
		actv.setAdapter(adapter);
	}
           

 多次提示

Android常用UI

 XML檔案:

<MultiAutoCompleteTextView
    	android:id="@+id/mactv"
    	android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:completionThreshold="1"
    	/>
           

Java代碼:

private void generateMactv() {
		MultiAutoCompleteTextView mactv = (MultiAutoCompleteTextView) findViewById(R.id.mactv);
		String[] items = { "tom", "tony", "terry", "付東", "付榮", "付貴" };
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, items);
		mactv.setAdapter(adapter);
		//用分隔符進行分割
		mactv.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
	}