Android控件之AutoCompleteTextView的使用
首先:我们在布局文件activity_main.xml中定义一个AutoCompleteTextView控件。
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.android_autocompletetextview.MainActivity$PlaceholderFragment" >
<AutoCompleteTextView
android:id="@+id/countries"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:layout_toRightOf="@+id/cities"
android:ems="10"
android:text="" />
<TextView
android:id="@+id/cities"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="@+id/autoCompleteTextView1"
android:textSize="20sp"
android:text="所属城市" />
</RelativeLayout>
第二:在src下Java的MainActivity类
public class MainActivity extends Activity {
private AutoCompleteTextView textView;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (AutoCompleteTextView) this.findViewById(R.id.countries);
//在Java代码中写适配器数据
/*adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getDataString());*/
//在配置资源文件中加载数据
String [] cities = getResources().getStringArray(R.array.cities);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cities);
textView.setAdapter(adapter);
//在资源文件中配置数据源
}
//数据源
public List<String> getDataString(){
List<String> list = new ArrayList<String>();
list.add("Bei jing");
list.add("shang hai");
list.add("shen zheng");
return list;
}
}
第三:效果截图类似