AutoCompleteTextView自动提示控件的使用(by 星空武哥)

版权声明:本文为博主原创文章,未经博主允许不得转载。 

使用方式和listView类似,有两种方式。

第一种:使用字符串数组为内容来源:

        1.在Activity布局文件activity_main.xml中创建一个 AutoCompleteTextView 控件 

      android:completionThreshold="1" 指定了几个字母开始自动补全,这里设置成个字母就补全。

1
2
3
4
5
6
7
8
9
10
11
12
13
< 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 = ".MainActivity"  >
 
     < AutoCompleteTextView
         android:completionThreshold = "1"
         android:layout_width = "fill_parent"
         android:layout_height = "wrap_content"
         android:id = "@+id/act_city"  />
 
</ RelativeLayout >

         2.创建一个适配器的布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<? 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:layout_width = "fill_parent"
         android:layout_height = "wrap_content"
         android:id = "@+id/item_city"
         
         />
 
</ LinearLayout >

使用步骤:

        1.找控件
            AutoCompleteTextView act_city = (AutoCompleteTextView) findViewById(R.id.act_city);
        2.创建一个Adpater
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.item_auto_city, R.id.item_city, citys);
        3.设置adaper
            act_city.setAdapter(arrayAdapter)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public  class  MainActivity  extends  Activity {
     // 创建数组
     String [] citys =  new  String[] { "河北" , "河南" , "山东" , "shanxi" , "hunan" , "hubei" };
 
     @Override
     protected  void  onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         
         AutoCompleteTextView act_city = (AutoCompleteTextView) findViewById(R.id.act_city);
         //创建一个Adpater
         ArrayAdapter<String> arrayAdapter =  new  ArrayAdapter<String>( this , R.layout.item_auto_city, R.id.item_city, citys);
         //设置adaper
         act_city.setAdapter(arrayAdapter);
         
     }
}


第二种方法:使用XML为数据来源

下面是xml文件,在values/strings.xml中


 <string-array name="str">
        <item>ShanDong</item>
        <item>ShanXi</item>
        <item>HeNan</item>
   	</string-array>
下面设置ArrayAdapter
ArrayAdapter adapter=ArrayAdapter.createFromResource(this, R.array.str, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        tv.setAdapter(adapter);








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值