您好,登錄后才能下訂單哦!
在 Android 中,要實(shí)現(xiàn) EditText 的自動(dòng)補(bǔ)全功能,可以使用 AutoCompleteTextView 組件。AutoCompleteTextView 是 EditText 的一個(gè)子類,它可以在用戶輸入時(shí)顯示建議列表。以下是如何實(shí)現(xiàn) AutoCompleteTextView 的簡單示例:
<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="請輸入內(nèi)容" />
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ù)輸入以縮小選擇范圍。
免責(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)容。