星期二, 10月 04, 2011

實作AutoCompleteTextView

實作AutoCompleteTextView

1.XML文件

  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. <TextView  
  8.     android:layout_width="fill_parent" 
  9.     android:layout_height="wrap_content" 
  10.     android:text="@string/hello"
  11.     />
  12. <AutoCompleteTextView 
  13. android:id="@+id/autoCompleteTextView1" 
  14. android:text="" 
  15. android:layout_width="fill_parent" 
  16. android:layout_height="wrap_content">
  17.     <requestFocus></requestFocus>
  18. </AutoCompleteTextView>
  19. </LinearLayout>



2.java文件
  1. package test.AutoCompleteTextView;

  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.widget.ArrayAdapter;
  5. import android.widget.AutoCompleteTextView;

  6. public class HelloAutoCompleteTextViewActivity extends Activity {
  7.     /** Called when the activity is first created. */
  8. //宣告一個AutoCompleteTextView物件為actv
  9. //實現ArrayAdapter產生str字串陣列的適配器
  10. //setAdapter()將適配器設定給actv
  11. private AutoCompleteTextView actv;
  12.     @Override
  13.     public void onCreate(Bundle savedInstanceState) {
  14.         super.onCreate(savedInstanceState);
  15.         setContentView(R.layout.main);
  16.         
  17.         actv = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
  18.         String[] str = {"abc" , "abcd" , "bcd" , "bcde"};
  19.         
  20.        ArrayAdapter adapter = new ArrayAdapter(this , android.R.layout.simple_dropdown_item_1line , str);
  21.        actv.setAdapter(adapter);
  22.     }
  23. }

沒有留言:

張貼留言