转自:http://blog.csdn.net/qq_28468727/article/details/52258409
AutoCompleteTextView、MultiAutoCompleteTextView自动完成输入内容的控件
如果我们想实现用户输入的内容有自动提示功能,类似百度搜索结果,AutoCompleteTextView和MultiAutoCompleteTextView可以实现类似功能
MainActivity.JAVA:
public class MainActivity extends AppCompatActivity { private AutoCompleteTextView autoTextView; private MultiAutoCompleteTextView multiAutoCompleteTextView; private ArrayList<String> list; private ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); autoTextView = (AutoCompleteTextView) findViewById(R.id.autotext); multiAutoCompleteTextView = (MultiAutoCompleteTextView) findViewById(R.id.multiauto); //对list进行初始化 list = new ArrayList<String>(); list.add("123456"); list.add("12345"); list.add("1234"); list.add("google"); list.add("goole map"); list.add("goole chrome"); //使用list中的数据对适配器adapter进行初始化 //第二个参数表示适配器为下拉风格 adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,list); //为AutoCompleteTextView添加适配器 autoTextView.setAdapter(adapter); //multiAutoCompleteTextView添加适配器 multiAutoCompleteTextView.setAdapter(adapter); //完成对选项的拆分,以逗号隔开 multiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()); } }
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.administrator.edittextdemo.MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textview1" android:text="AutoCompleteTextView"/> <AutoCompleteTextView android:id="@+id/autotext" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textview2" android:text="MultiAutoCompleteTextView"/> <MultiAutoCompleteTextView android:id="@+id/multiauto" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>