[英]Auto Complete Hint with Material in Android
我在材料文本字段中阅读了文档,并且在 editText 上有 auto-complete-textView 作为提示而不是下拉菜单。 你可以看到下面的图片。 但我做不到。 我尝试了一些带有 textinputlayout 和 material-auto-complete-text 的代码,如下所示
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/til"
..>
<com.google.android.material.textfield.MaterialAutoCompleteTextView
.../>
</com.google.android.material.textfield.TextInputLayout>
在片段中
ArrayList<String> items = new ArrayList<>();
items.add("Material");
items.add("Design");
items.add("Components");
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,R.layout.item, items);
TextInputLayout textInputLayout = findViewById(R.id.til);
并设置适配器
((MaterialAutoCompleteTextView) textInputLayout.getEditText()).setAdapter(adapter);
((MaterialAutoCompleteTextView) textInputLayout.getEditText()).setText(adapter.getItem(1),false);
但是 auto-complete-textview 建议下拉而不是 editText 上的项目作为提示。
我想要AutoC omplete 因为“AutoC”必须是文本并且“omplete”必须是提示
我该怎么做??
以下是您要查找的内容吗? (它将根据用户输入设置提示。但这不能用于实际的自动完成,因为据我所知,您无法更改键盘上的建议):
TextInputEditText editText = ((TextInputEditText) textInputLayout.getEditText());
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
try {
String userInput = s.toString();
userInput = userInput.trim().toLowerCase();
String match = null;
for (String item : items) {
if (item == null) continue;
String fItem = item.trim().toLowerCase();
if (fItem.startsWith(userInput)) {
match = item;
break;
}
}
if (match == null) editText.setHint(""); // Insert your default hint text here
else editText.setHint(match);
} catch (Throwable tr) {
tr.printStackTrace();
}
}
});
将以下内容作为属性添加到您的 TextInputLayout:
style="@style/Widget.MaterialComponents.TextInputLayout.*.ExposedDropdownMenu"
您是否也正确实现了您的 list_item.xml (您将其称为“项目”(代码中的 R.layout.item))?
官网上是这么写的:
在布局中:
<com.google.android.material.textfield.TextInputLayout
...
style="@style/Widget.MaterialComponents.TextInputLayout.*.ExposedDropdownMenu">
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="none"
/>
</com.google.android.material.textfield.TextInputLayout>
在代码中:
val items = listOf("Material", "Design", "Components", "Android")
val adapter = ArrayAdapter(requireContext(), R.layout.list_item, items)
(textField.editText as? AutoCompleteTextView)?.setAdapter(adapter)
在项目布局 (list_item.xml) 中:
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:ellipsize="end"
android:maxLines="1"
android:textAppearance="?attr/textAppearanceSubtitle1"
/>
( https://material.io/components/text-fields/android#using-text-fields )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.