溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android EditText自動(dòng)補(bǔ)全功能實(shí)現(xiàn)

發(fā)布時(shí)間:2024-08-31 15:39:44 來源:億速云 閱讀:87 作者:小樊 欄目:移動(dòng)開發(fā)

在 Android 中,要實(shí)現(xiàn) EditText 的自動(dòng)補(bǔ)全功能,可以使用 AutoCompleteTextView 組件。AutoCompleteTextView 是 EditText 的一個(gè)子類,它可以在用戶輸入時(shí)顯示建議列表。以下是如何實(shí)現(xiàn) AutoCompleteTextView 的簡單示例:

  1. 在布局文件(例如 activity_main.xml)中添加 AutoCompleteTextView 控件:
<AutoCompleteTextView
    android:id="@+id/autoCompleteTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="請輸入內(nèi)容" />
  1. 在 Activity(例如 MainActivity.java)中設(shè)置適配器:
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 創(chuàng)建一個(gè)包含建議內(nèi)容的字符串?dāng)?shù)組
        String[] suggestions = {"Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"};

        // 創(chuàng)建一個(gè) ArrayAdapter,將建議內(nèi)容與 AutoCompleteTextView 關(guān)聯(lián)
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, suggestions);

        // 獲取布局文件中的 AutoCompleteTextView 控件
        AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autoCompleteTextView);

        // 為 AutoCompleteTextView 設(shè)置適配器
        autoCompleteTextView.setAdapter(adapter);
    }
}

在這個(gè)示例中,我們首先在布局文件中添加了一個(gè) AutoCompleteTextView 控件。然后,在 Activity 中,我們創(chuàng)建了一個(gè)包含建議內(nèi)容的字符串?dāng)?shù)組,并使用 ArrayAdapter 將其與 AutoCompleteTextView 關(guān)聯(lián)。最后,我們獲取布局文件中的 AutoCompleteTextView 控件,并為其設(shè)置適配器。

現(xiàn)在,當(dāng)用戶在 AutoCompleteTextView 中輸入內(nèi)容時(shí),應(yīng)用程序?qū)@示與輸入內(nèi)容相匹配的建議列表。用戶可以從列表中選擇一個(gè)建議,或者繼續(xù)輸入以縮小選擇范圍。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI