編輯:關於 Android 程式設計

AutoCompleteTextView 是可編輯的文本輸入框,但它多做了一件事:當用戶輸入字符時,會自動彈出一個下拉列表,展示所有與已輸入內容匹配的候選項,讓用戶直接點選,省去完整輸出的麻煩。本質上它是 EditText 加上一個 ListView 的組合體。
1. setThreshold(int)
設置觸發提示的最小字符數。比如設為 3,用戶必須輸入滿 3 個字符,下拉列表才會出現。這個值不宜太小,否則用戶剛打一個字母就彈出一大堆結果,反而干擾;也不宜太大,否則失去自動完成的意义。
2. setCompletionHint(CharSequence)
設置提示文案。當輸入框為空、下拉列表尚未出現時,會在後方顯示一段灰色的引導文字,告訴用戶該輸入什麼。
3. setAdapter()
綁定數據源。這是最關鍵的一步,通常傳一個 ArrayAdapter 或自定義 CursorAdapter,候選數據從哪裡來完全由它決定。
4. setDropDownBackgroundResource(int)
設置下拉列表的背景。和它等價的還有一個 setDropDownBackgroundDrawable(Drawable),可以傳入自定義的 Drawable 對象,實現圓角、漸變等更複雜的效果。
5. setDropDownAnchor() 與 setDropDownWidth()
分別用來指定下拉列表的錨點 View 和寬度,需要讓下拉框對齊到某個特定控件時會用到。
public class MainActivity extends Activity {
AutoCompleteTextView autoCompleteTextView;
String[] str = { "peach", "Pear", "Banana", "honeydew", "orange", "tangerine" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.myview);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
MainActivity.this,
android.R.layout.simple_dropdown_item_1line, str);
// 輸入 3 個字符後開始匹配
autoCompleteTextView.setThreshold(3);
// 提示信息
autoCompleteTextView.setCompletionHint("選擇一項");
// 下拉列表背景
autoCompleteTextView.setDropDownBackgroundResource(R.drawable.blue);
autoCompleteTextView.setAdapter(arrayAdapter);
}
}
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<AutoCompleteTextView
android:id="@+id/myview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

上面示例用的是靜態數組,實際項目中候選數據往往來自網絡或數據庫,這時更合適的做法是繼承 BaseAdapter 自行實現一個支持按關鍵字過濾的適配器,並在 performFiltering() 中做異步查詢。
還有一個容易忽略的點:AutoCompleteTextView 默認只匹配「開頭」。也就是說輸入 "an" 能匹配到 "Banana" 之外的項?其實不行——默認的 ArrayAdapter 過濾器只對前綴匹配。如果需要包含匹配,得自定義 Filter。另外若希望用戶能自由輸入任意內容而不受限於列表,可以在佈局中設置 android:completionThreshold 並配合 setThreshold(1),或者乾脆考慮使用普通的 EditText。
最後提醒:AutoCompleteTextView 的默認輸入類型可能導致彈出軟鍵盤時的建議欄與自己的下拉列表打架,必要時可以設置 android:inputType="textNoSuggestions" 來避免干擾。
Android 事件分發機制透徹分析(附完整 Log 驗證)
先把觸摸事件相關的方法列出來。 ViewGroup: · dispatchTouchEvent(MotionEvent):用於分發 touch 事件 · onInterc
Android 三種對話框寫法總結:AlertDialog、Dialog 與 Activity 樣式視窗
專案裡對話框的需求大致分三類:單純的確認提示、需要自訂版面的進度提示、以及需要輸入資料的表單。這三種對應三種不同的實作方式,本篇逐一整理。 一、AlertDialog:
自訂 View 打造溫度調節旋鈕:刻度盤與滑動交互
冷氣、烤箱這類應用的溫度設定,用旋鈕比用輸入框直覺得多。本文示範如何從零繪製一個 270° 的弧形刻度盤,並讓中央的旋鈕按鈕跟著手指轉動。 成品效果: 溫度旋轉按鈕
Android 屬性動畫進階:補充說明與實用技巧
目錄 本文概述、動畫補充說明、屬性動畫的 View 加載方式、TypeEvaluator 的使用、TimeInterpolator、LayoutTransition、Ot