溫馨提示×

edittext自動補全功能怎樣開啟

小樊
84
2024-07-02 14:39:44
欄目: 編程語言

要開啟EditText的自動補全功能,可以使用setAdapter()方法來設置一個適配器,適配器可以提供自動補全的建議列表。以下是一個簡單的示例代碼:

ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, new String[]{"apple", "banana", "cherry"});
EditText editText = findViewById(R.id.editText);
editText.setAdapter(adapter);

在這個示例中,我們創(chuàng)建了一個ArrayAdapter對象,然后傳入一個包含一些單詞的字符串數(shù)組。然后調(diào)用editText的setAdapter()方法將適配器設置到EditText上,這樣用戶在輸入時就會看到自動補全的建議。

另外,你也可以通過在布局文件中設置android:completionThreshold屬性來指定多少個字符后開始顯示自動補全的建議。例如:

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:completionThreshold="1" />

上面代碼中的android:completionThreshold="1"表示用戶輸入一個字符后就會顯示自動補全的建議列表。

0