我的android學習經曆12,android學習經曆12
自動匹配輸入的內容(文章最後有一個問題有興趣的可以解答一下,謝謝大神了)
這個主要是兩個控制項MultiAutoCompleteTextView和AutoCompleteTextView
這兩個控制項和TextView的主要區別就是可以自動匹配使用者輸入的內容,就像百度,在百度的搜尋方塊中輸入資訊時,會提示你一些資訊
這兩個控制項的屬性主要比TextView多了一個屬性 android:completionThreshold="2",這個屬性主要是來說明使用者輸入多少字元時開始匹配(我這裡是兩個字元);
(1)先講一下AutoCompleteTextView的實現
布局檔案中有關的代碼如下(主要的屬性大家都認識,綠色的為特有的屬性)
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView1"
android:hint="請輸入內容"
android:textColor="#000000"
android:completionThreshold="2"
>
<requestFocus />
</AutoCompleteTextView>
在原始碼檔案中的代碼為
private AutoCompleteTextView auTextView;
String []res={"ab1","ab2","ab3","ab4","ab5"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auTextView=(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
//定義適配器並且添加適配器
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, res);
auTextView.setAdapter(adapter);
}
如下:
(2)MultiAutoCompleteTextView的實現
它和AutoCompleteTextView的主要區別就在於它可以多次匹配,只要定義了分隔字元,而AutoCompleteTextView只可以進行一次匹配
它在布局檔案中的代碼為
<MultiAutoCompleteTextView
android:id="@+id/multiAutoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/autoCompleteTextView1"
android:layout_marginTop="24dp"
android:textColor="#000000"
android:completionThreshold="2"
android:hint="請輸入內容" />
它在代碼檔案中的代碼為:
private MultiAutoCompleteTextView muTextView;
String []res={"ab1","ab2","ab3","ab4","ab5"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//定義適配器並且添加適配器
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, res);
muTextView=(MultiAutoCompleteTextView)findViewById(R.id.multiAutoCompleteTextView1);
muTextView.setAdapter(adapter);
//設定逗號分隔字元
muTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
}
如下:
那個設定分隔字元的時候我不太懂我查了一下主要是用到了new MultiAutoCompleteTextView.CommaTokenizer(),不知道為什麼這個就是逗號分隔字元,希望大神可以解答,謝謝
有什麼錯誤的地方請指出,謝謝