AutoCompleteTextView可以像Google搜索一样,当你在搜索框里输入一些字符时(至少两个字符),会自动弹出一个下拉框提示类似的结果,如下图 极大地提高用户体验。下面我们来一步一步实现这个效果,先是布局xml,main.xml内容:
<AutoCompleteTextView android:id="@+id/auto_complete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
接着是程序代码:
package com.pocketdigi;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String[] strings=new String[]{"abc","abd","abe","bcd","bce","bcf"};
//预定义字符串
ArrayAdapter adapter=new ArrayAdapter(this,
android.R.layout.simple_dropdown_item_1line,strings);
AutoCompleteTextView actv=(AutoCompleteTextView)findViewById(R.id.auto_complete);
actv.setThreshold(1);//设置输入多少字符后提示,默认值为2
actv.setAdapter(adapter);
}
}
取值方法与普通文本框EditText相同
String v=actv.getText().toString();