在本节中作者只写了AutoCompleteTextView 和MutiAutoCompleteTextView 的用法,没有写怎样得到选中的值,我做了如下修改,增加按钮获取值赋值给TextView
-
public class MainActivity extends Activity {
-
AutoCompleteTextView actv;
-
TextView textView;
-
Button button;
-
String string;
-
// 定义字符串数组,作为提示的文本
-
String[] books = new String[]{
-
"疯狂Java讲义",
-
"疯狂Ajax讲义",
-
"疯狂XML讲义",
-
"疯狂Workflow讲义"
-
};
-
@Override
-
public void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_main1);
-
textView = (TextView) findViewById(R.id.textv);
-
button = (Button) findViewById(R.id.search);
-
// 创建一个ArrayAdapter,封装数组
-
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
-
android.R.layout.simple_dropdown_item_1line, books);
-
actv = (AutoCompleteTextView) findViewById(R.id.auto);
-
// 设置Adapter
-
actv.setAdapter(adapter);
-
//textView.setText(actv.getText().toString());
-
// 设置监听事件,点击搜索写入搜索词
-
button.setOnClickListener(new Button.OnClickListener() {
-
@Override
-
public void onClick(View v) {
-
// TODO Auto-generated method stub
-
string=actv.getText().toString();
-
textView.setText(string);
-
}
-
});
-
-
}
-
}
|
对应的xml文件
-
<?xml version="1.0" encoding="utf-8"?>
-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-
android:orientation="vertical"
-
android:layout_width="match_parent"
-
android:layout_height="match_parent">
-
<!-- 定义一个自动完成文本框,指定输入一个字符后进行提示 -->
-
<TextView
-
android:id="@+id/textv"
-
android:layout_marginTop="60dp"
-
android:textSize="29dp"
-
android:text="输入的名称"
-
android:textColor="@android:color/holo_red_light"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"/>
-
<LinearLayout
-
android:layout_width="match_parent"
-
android:orientation="horizontal"
-
android:layout_height="wrap_content">
-
<AutoCompleteTextView
-
android:id="@+id/auto"
-
android:layout_width="0dp"
-
android:layout_weight="1"
-
android:layout_height="wrap_content"
-
android:completionHint="请选择您喜欢的图书:"
-
android:dropDownHorizontalOffset="10dp"
-
android:completionThreshold="1"/>
-
<Button
-
android:id="@+id/search"
-
android:layout_width="wrap_content"
-
android:layout_height="wrap_content"
-
android:text="搜索" />
-
</LinearLayout>
-
</LinearLayout>
|
效果: