AutoCompleteTextView

在本节中作者只写了AutoCompleteTextView MutiAutoCompleteTextView 的用法,没有写怎样得到选中的值,我做了如下修改,增加按钮获取值赋值给TextView

  1. public class MainActivity extends Activity {
  2. AutoCompleteTextView actv;
  3. TextView textView;
  4. Button button;
  5. String string;
  6. // 定义字符串数组,作为提示的文本
  7. String[] books = new String[]{
  8. "疯狂Java讲义",
  9. "疯狂Ajax讲义",
  10. "疯狂XML讲义",
  11. "疯狂Workflow讲义"
  12. };
  13. @Override
  14. public void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.activity_main1);
  17. textView = (TextView) findViewById(R.id.textv);
  18. button = (Button) findViewById(R.id.search);
  19. // 创建一个ArrayAdapter,封装数组
  20. ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
  21. android.R.layout.simple_dropdown_item_1line, books);
  22. actv = (AutoCompleteTextView) findViewById(R.id.auto);
  23. // 设置Adapter
  24. actv.setAdapter(adapter);
  25. //textView.setText(actv.getText().toString());
  26. // 设置监听事件,点击搜索写入搜索词
  27. button.setOnClickListener(new Button.OnClickListener() {
  28. @Override
  29. public void onClick(View v) {
  30. // TODO Auto-generated method stub
  31. string=actv.getText().toString();
  32. textView.setText(string);
  33. }
  34. });
  35.  
  36. }
  37. }

对应的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="match_parent"
  5. android:layout_height="match_parent">
  6. <!-- 定义一个自动完成文本框,指定输入一个字符后进行提示 -->
  7. <TextView
  8. android:id="@+id/textv"
  9. android:layout_marginTop="60dp"
  10. android:textSize="29dp"
  11. android:text="输入的名称"
  12. android:textColor="@android:color/holo_red_light"
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"/>
  15. <LinearLayout
  16. android:layout_width="match_parent"
  17. android:orientation="horizontal"
  18. android:layout_height="wrap_content">
  19. <AutoCompleteTextView
  20. android:id="@+id/auto"
  21. android:layout_width="0dp"
  22. android:layout_weight="1"
  23. android:layout_height="wrap_content"
  24. android:completionHint="请选择您喜欢的图书:"
  25. android:dropDownHorizontalOffset="10dp"
  26. android:completionThreshold="1"/>
  27. <Button
  28. android:id="@+id/search"
  29. android:layout_width="wrap_content"
  30. android:layout_height="wrap_content"
  31. android:text="搜索" />
  32. </LinearLayout>
  33. </LinearLayout>

效果:

原文地址:https://www.cnblogs.com/wwjldm/p/6929471.html