天天看點

AutoCompleteTextView資料綁定

首先,在布局檔案main.xml中添加AutoCompleteTextView元件,代碼如下:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     android:orientation="vertical" 
  4.     android:layout_width="fill_parent" 
  5.     android:layout_height="fill_parent" 
  6.     > 
  7. <AutoCompleteTextView 
  8.     android:id="@+id/auto_complete"   
  9.     android:layout_width="fill_parent"   
  10.     android:layout_height="wrap_content" 
  11.     /> 
  12. </LinearLayout> 
然後在MainActivity.java中定義需要綁定的資料,并将其綁定到元件上。代碼如下:
  1. public class MainActivity extends Activity {  
  2.     // 定義一組需要綁定的資料  
  3.     private static final String[] COUNTRIES = new String[] { "China", "Russia",  
  4.             "Germany", "USA", "Chinal", "Germany1", "China12" };  
  5.     /** Called when the activity is first created. */ 
  6.     @Override 
  7.     public void onCreate(Bundle savedInstanceState) {  
  8.         super.onCreate(savedInstanceState);  
  9.         setContentView(R.layout.main);  
  10.         // 進行資料綁定  
  11.         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,  
  12.                 android.R.layout.simple_dropdown_item_1line, COUNTRIES);  
  13.         AutoCompleteTextView textview = (AutoCompleteTextView) findViewById(R.id.auto_complete);  
  14.         textview.setAdapter(adapter);  
  15.     }