Android中如何使用AutoCompleteTextView

今天新學了一個AutoCompleteTextView高級控件,當初寫Java實現Ajax自動補全的時候就感覺很好玩,今天使用AutoCompleteTextView後感覺更簡單了,所以特意整理一下分享出來

實現思路:

第一步:在xml中用一個AutoCompleteTextView標籤、competionThreshold是從第幾個字開始

第二步:編輯相對應的java,獲取控件AutoCompleteTextView

第三步:在res-values-strings.xml中定義一個string-array,標籤內寫item

第四步:再回到java代碼中,獲取第三步定義的string-array

第五步:實例化一個適配器,設置參數,第二個參數需要在layout中實例化一個xml,爲你自己的內容寫一個TextView的控件,只需要一個,所以要改掉根標籤,只存在一個TextView。

第六步:在java代碼中給控件設置適配器


xml中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.g160628_android07_widgetplus.MainActivity">
    <!--定義一個AutoCompleteTextView
        設置當文本框有一個字的時候進行補全(設置completionThreshold)
    -->
    <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:completionThreshold="1"
        android:id="@+id/actv_main_auto"
        />

</LinearLayout>
java中:

package com.example.g160628_android07_widgetplus;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class MainActivity extends AppCompatActivity {

    private AutoCompleteTextView actv_main_auto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //根據id獲取你的AutoCompleteTextView
        actv_main_auto = (AutoCompleteTextView) findViewById(R.id.actv_main_auto);

        //獲取value中的字符串數組
        String data[]=getResources().getStringArray(R.array.data);
        //實例化一個適配器(適配器的參數爲,上下文,文本格式,數組)
        ArrayAdapter adapter=new ArrayAdapter(this,R.layout.item_actv,data);
        //給控件設置適配器
        actv_main_auto.setAdapter(adapter);
    }
}
layout中的xml文本格式

<?xml version="1.0" encoding="utf-8"?>
<!--
        自己寫的一個文本格式
-->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tv_item_actv_text"
    android:textSize="30sp"
    >

</TextView>
strings.xml

<resources>
    <string name="app_name">G160628_android07_widgetPlus</string>
    <!--
        定義一個string-array,並命一個名字
    -->
    <string-array name="data">
        <item>張三</item>
        <item>張三丰</item>
        <item>李四</item>
        <item>李四他爹</item>
        <item>王五</item>
        <item>王二小</item>
        <item>蛋蛋</item>
        <item>狗蛋</item>
        <item>妞妞</item>
        <item>二狗子</item>
    </string-array>
</resources>

歡迎各位指點一二
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章