本文介紹的是Android常用控件AutoCompleteTextView的使用方法
下面是導讀:
1.什麼時AutoCompleteTextView
2.如何使用AutoCompleteTextView
3.總結
1.什麼是AutoCompleteTextView?
在輸入框中輸入我們想要輸入的信息就會出現其他與其相關的提示信息,這種效果在Android中是用AutoCompleteTextView實現的。
下圖是Android6.0系統的AutoCompleteTextView樣式:
2.如何使用AutoCompleteTextView?
第一步:在佈局文件中創建AutoCompleteTextView
<AutoCompleteTextView
android:layout_width="384dp"
android:layout_height="wrap_content"
android:id="@+id/auto"
android:hint="自動補全demo"
android:textSize="16sp"
tools:layout_editor_absoluteY="318dp"
app:layout_constraintRight_toRightOf="@+id/seekBar"
android:layout_below="@+id/date_java"
android:layout_alignParentEnd="true"
android:layout_marginEnd="10dp" />
第二步:定義提示條目樣式
新建list_item.xml佈局文件,內容如下
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:app="http://schemas.android.com/apk/res/android"
app:layout_width="match_parent"
app:layout_height="50dp"
app:background="#43fdfdfd"
app:paddingStart="10dp"
>
</TextView>
(佈局是可以隨意發揮的,按照你的審美觀點走)
第三步:這一步可以分兩種方法,根據需要,可以選不同的方法
準備工作:
在Activity類中初始以下數據(直接寫在public xxx extends Activity的中括號裏最前面)
AutoCompleteTextView autoCompleteTextView=null;
static final String[] COUNT=new String[]
{
"ab","cd","as","de","cg","sddfd","sdde","sfs","fff"
,"sss","ffe","sfg","sed","dfg","qwe","dfss",
"ddf","dfsd","ddfg"
};
//這裏的數據都是固定的,提前設計好的
首先是動態數據:
在onCreate()方法裏寫以下代碼:
//初始化auto對象
autoCompleteTextView= (AutoCompleteTextView) findViewById(R.id.auto);
//創建一個list,爲其提供數據
List<String> list =new ArrayList<String>();
list.add("測試");
list.add("測試2");
list.add("測試xx");
list.add("xx測試");
//設置適配器
ArrayAdapter<String> arrayAdapter =new ArrayAdapter<String>(this,R.layout.list,list);
//綁定適配器
autoCompleteTextView.setAdapter(arrayAdapter);
靜態數據
在onCreate()方法裏寫以下代碼:
//auto對象
autoCompleteTextView= (AutoCompleteTextView) findViewById(R.id.auto);
//傳入提前聲明好的數據
ArrayAdapter<String> arrayAdapter =new ArrayAdapter<String>(this,R.layout.list,COUNT);
//綁定適配器
autoCompleteTextView.setAdapter(arrayAdapter);
3.總結
簡單的配置已經完全可以達到使用目的,具體的美化就要發揮你的審美能力嘍
補充:
AutoCompleteTextView常用的xml屬性
android:completionHint 設置出現在下拉菜單中的提示標題
android:completionThreshold 設置用戶至少輸入多少個字符纔會顯示提示
android:dropDownHorizontalOffset 下拉菜單于文本框之間的水平偏移。默認與文本框左對齊
android:dropDownHeight 下拉菜單的高度
android:dropDownWidth 下拉菜單的寬度
android:singleLine 單行顯示
android:dropDownVerticalOffset 垂直偏移量