android如何将EditText用作AutoComplete

Jyo*_*sna 37 android android-edittext

我想我EditText应该工作AutoComplete,因为我写的是XML文件

android:inputType="textAutoComplete|textAutoCorrect"
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

我正在使用API​​ v2.2和我的Activity扩展MapActivity,在那里我放了一个简单EditText的按钮,名为"搜索".因此,如果我们输入位置名称EditText并按下搜索按钮,则表示它应该转到地图中的该位置.所以我希望这EditText可以作为一个AutoComplete.我怎样才能做到这一点?

Arn*_*rty 52

只需使用一个AutoCompleteTextView而不是正常EditText.

你好自动完成将是有帮助的.


Bes*_*ohn 17

首先转换你的 EditText->AutoCompleteTextView

然后将您的XML文件链接到AutoCompleteTextView使用aArrayAdapter

假设string-array您创建的XML 被命名为list_of_countries然后它可以链接到您AutoCompleteTextView,如下所示:

String[] countries = getResources().getStringArray(R.array.list_of_countries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,countries);
actv.setAdapter(adapter);
Run Code Online (Sandbox Code Playgroud)


mgh*_*hgm 9

我用这个代码:

在此输入图像描述

1)在AndroidManifest.xml上

<uses-permission android:name="android.permission.GET_ACCOUNTS"></uses-permission>
Run Code Online (Sandbox Code Playgroud)

2)在xml布局上,您必须使用AutoCompleteTextView而不是EditText.

<AutoCompleteTextView
    android:id="@+id/autoCompleteTextView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:text="AutoCompleteTextView" />
Run Code Online (Sandbox Code Playgroud)

3)在Activity文件中使用它

private ArrayAdapter<String> getEmailAddressAdapter(Context context) {
    Account[] accounts = AccountManager.get(context).getAccounts();
    String[] addresses = new String[accounts.length];
    for (int i = 0; i < accounts.length; i++) { 
        addresses[i] = accounts[i].name;
    }
    return new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, addresses);
}
Run Code Online (Sandbox Code Playgroud)

4)关于onCreate活动:

AutoCompleteTextView autoCompleteTextView1 = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
autoCompleteTextView1.setAdapter(getEmailAddressAdapter(this));
Run Code Online (Sandbox Code Playgroud)

  • 这仅在用户开始输入后显示建议。另外我不确定 android M 中的新权限是否安全。 (2认同)