我正在开发一个使用 AutoCompleteTextView 的应用程序,但遇到了一些问题。请在下面查找问题的详细信息。
数据中存在以下值:
1)曼尼什·洛根·杰恩
2)M.J.(洛根·费恩)
3)洛根
问题:
1) 当用户搜索 Manish 时,Manish Logan Jain 会作为建议显示。但是当用户输入 Logan Jain 时,不会返回任何结果。
2)当用户输入 Logan 时,我希望第二个值显示为建议,但目前建议列表什么也不显示。
3) 当用户输入 ogan 时,我希望显示建议 3。目前,尚未显示。
自动完成 View xml:
自动完成 TextView
android:id="@+id/autoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="@string/enter_user_name" >
<requestFocus />
</AutoCompleteTextView>
填充数据的 Java 代码:
List<String> namesList = new ArrayList<String>(stops);
namesList.add("Manish Logan Jain");
namesList.add("Logan");
namesList.add("M. J. (Logan Fern)");
ArrayAdapter<String> namesSuggestion = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, namesList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
textView.setAdapter(namesSuggestion);
textView.setThreshold(1);
有人遇到过类似的问题吗?如果是,那么可能的解决方案是什么?
最佳答案
为您的 ACTV 使用 CursorAdapter 并调用 setFilterQueryProvider(FilterQueryProvider) 进行自定义过滤(使用 MatrixCursor 来过滤数据)
编辑:示例 FilterQueryProvider
class FQP extends LinkedList<String> implements FilterQueryProvider {
@Override
public Cursor runQuery(CharSequence constraint) {
if (constraint == null) {
return null;
}
Log.d("TAG", "runQuery " + constraint);
String lowerConstraint = constraint.toString().toLowerCase();
String[] columns = {
"_id", "name"
};
int id = 0;
MatrixCursor c = new MatrixCursor(columns);
for (String name : this) {
String lowerName = name.toLowerCase();
if (lowerName.indexOf(lowerConstraint) != -1) {
c.newRow().add(id++).add(name);
}
}
return c;
}
};
在 onCreate 中使用以下内容进行测试:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
AutoCompleteTextView actv = new AutoCompleteTextView(this);
String[] from = {"name"};
int[] to = {android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to);
FQP fqp = new FQP();
fqp.add("Manish Logan Jain");
fqp.add("Logan");
fqp.add("M. J. (Logan Fern)");
adapter.setFilterQueryProvider(fqp);
actv.setAdapter(adapter);
actv.setThreshold(1);
ll.addView(actv);
setContentView(ll);
关于java - AutoCompleteTextView 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21087111/