Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Android AutoCompleteTextView 打造自動補全輸入框

編輯:關於 Android 程式設計

我們在使用百度或 Google 搜尋時,只要輸入一兩個字,系統就會自動提示可能想找的內容。這種「自動補全」的體驗,在 Android 中可以透過 AutoCompleteTextView 搭配 ArrayAdapter 輕鬆實現。

實作原理

做法是:先在佈局中放入一個 AutoCompleteTextView,接著把預先準備好的字串陣列裝入 ArrayAdapter,最後呼叫 AutoCompleteTextView.setAdapter() 方法,就能讓它在使用者輸入時自動比對並提示。例如只要輸入 ab,就會自動帶出所有包含 ab 的字串。

Activity 程式碼

public class MainActivity extends Activity {
    private AutoCompleteTextView actv;
    private static final String[] autoStrs = new String[]{ "a", "abc", "abcde" };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        actv = (AutoCompleteTextView) findViewById(R.id.actv);
        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_dropdown_item_1line, autoStrs);
        actv.setAdapter(adapter);
    }
}

佈局檔

佈局中透過 android:completionThreshold 屬性,可以設定「至少輸入幾個字才開始比對提示」門檻:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <AutoCompleteTextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/actv"
        android:completionThreshold="1" /><!-- 設定只需輸入一個字就開始比對 -->
</LinearLayout>

透過 AutoCompleteTextView 與 ArrayAdapter 的簡單搭配,就能為輸入框賦予智慧提示能力,大幅提升使用者的輸入效率。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved