温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android自动补全提示

发布时间:2020-06-07 17:51:43 来源:网络 阅读:373 作者:mac_xiao 栏目:移动开发

    自动补全提示最主要的是使用AutoCompleteTextView控件,继而从与控件关联的ArrayAdapter提供的字符串集合得到提示。

    先上图

Android自动补全提示


AutoCompleteTextViewActivity.java代码如下:

public class AutoCompleteTextViewActivity extends Activity {
	   @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.autocomplete);
	        setTitle("AutoCompleteTextView_Activity");
	        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
	        	this,
	            android.R.layout.simple_dropdown_item_1line,
                COUNTRIES);//第2个参数是每个item的显示样式,第3个参数为提供数据的数组名
	        AutoCompleteTextView autotextView = (AutoCompleteTextView) findViewById(R.id.auto_complete);
	        autotextView.setAdapter(adapter);//将adapter适配器添加到auto..对象中
	        autotextView.setThreshold(1);//设置输入几个字母开始关联,默认是2(threshole:入口,门槛,临界值)
	    }
	static final String[] COUNTRIES = new String[] {    //设置数据源
		"China" ,"Russia", "Germany","Ukraine", "Belarus",
		"USA" ,"China1" ,"China12", "Germany1",
		"Russia2", "Belarus1", "USA1" 
	    };
}

layout中XML文件如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content">

   <AutoCompleteTextView android:id="@+id/auto_complete"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
</LinearLayout>

当然,为了以后修改数据源及代码的方便,建议将数据添加到在layout下的strings.xml文件中去

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <string-array name="countries_array">  
        <item>China</item>  
        <item>China1</item>  
        <item>China12</item>                 
    </string-array>  
</resources>

再将原先的数据源修改为如下即可

String[] COUNTRIES = getResources().getStringArray(R.array.countries_array);

注意:这条语句应写在new ArrayAdapter语句之前


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI