Android实现类似C#ComBox功能用AutoCompleteTextView实现

来源:互联网 发布:动漫和动画的区别 知乎 编辑:程序博客网 时间:2024/06/05 10:17

转载地址:http://blog.csdn.net/xujingqing/article/details/70208511


android实现既能单选又能输入的控件 很类似C#中ComBox控件;

public class MainActivity extends Activity {    private AutoCompleteTextView ac_1;    private ArrayList<String> list ;    private ArrayAdapter<String>adapter ;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        setView();        setListener();    }    private void setListener() {        ac_1.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                ac_1.showDropDown();//点击控件显示所有的选项            }        });    }    private void setView() {        ac_1 =(AutoCompleteTextView) findViewById(R.id.ac_1);        setData();        adapter =new ArrayAdapter<>(this, R.layout.item_ac, R.id.tv_1, list);        ac_1.setAdapter(adapter);    }    private void setData() {//设置数据源,这里只用了单纯的文字;        list =new ArrayList<>();        list .add("步行");        list .add("步行88");        list .add("轮椅");        list .add("轮椅77");        list .add("平车");        list .add("平车22");        list .add("担架");        list .add("担架3");        list .add("自行车");        list .add("自行车2");    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

下面是布局文件比较简单只有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"    tools:context="${relativePackage}.${activityClass}" >    <AutoCompleteTextView        android:id="@+id/ac_1"        android:completionThreshold="1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        /></RelativeLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

android:completionThreshold=”1”这个属性是输入框中输入几个字符开始有筛选提示功能; 
adapter =new ArrayAdapter<>(this, R.layout.item_ac, R.id.tv_1, list); 
创建适配器adapter时需要一个 上下文对象,一个布局文件,和显示文字用的TextView控件,最有一个是数据源;(如果传不同的数据源选用不同的Adapter); 
下面是这个布局文件:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/tv_1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="TextView" /></LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

这样就能像Spinner那样单选,又能像输入框一样输入。



阅读全文
0 0