【发布时间】:2014-11-26 13:55:49
【问题描述】:
美好的一天。我的 Android 应用程序中有一个 AutoCompleteTextView,它工作正常。但是,我注意到这些建议是基于提供给 AutoCompleteTextView 的列表的子字符串的第一个字符。这本身很好,但是,我想要的是它还显示包含用户输入的项目。
例如,让我们使用这个列表:
- 脂肪
- 坏狼
- 网络人
- 戴尔克斯
输入ad 将建议Adipose,但是,我也希望建议Bad Wolf,因为它在Bad 中包含ad。这不会发生,因为 AutoCompleteTextView 仅查看列表项中子字符串的开头(子字符串由空格分隔),而不是这些子字符串中。
有没有办法让 AutoCompleteTextViews 建议包含输入文本的项目,而不管该文本在列表项中的什么位置?
感谢您的帮助。
编辑/更新
请在下面查看 pskink 的评论。我尝试实现如下相同的解决方案。
我推断的逻辑是使用SimpleCursorAdapter,而不是常见的ArrayAdater。然后我为SimpleCursorAdapter 创建了一个FilterQueryProvider。使用FilterQueryProvider 的runQuery 方法,我现在可以通过搜索我的用户约束输入列表来运行过滤算法。代码如下:
//initialize the ACTV
AutoCompleteTextView search = (AutoCompleteTextView) findViewById(R.id.actvCatalogueSearch);
search.setThreshold(1); //set threshold
//experiment time!!
//I honestly don't know what this is for
int[] to = { android.R.id.text1 };
//initializing the cursorAdapter.
//please note that pdflist is the array I used for the ACTV value
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, null, pdflist, to, 0);
cursorAdapter.setStringConversionColumn(1);
//FilterQueryProvider here
FilterQueryProvider provider = new FilterQueryProvider(){
@Override
public Cursor runQuery(CharSequence constraint) {
// TODO Auto-generated method stub
Log.d("hi", "runQuery constraint: " + constraint);
if (constraint == null) {
return null;
}
String[] columnNames = { Columns._ID, "name" };
MatrixCursor c = new MatrixCursor(columnNames);
try {
//loop through the array, then when an array element contains the constraint, add.
for (int i = 0; i < pdflist.length; i++) {
if(pdflist[i].contains(constraint)){
c.newRow().add(i).add(pdflist[i]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
};
cursorAdapter.setFilterQueryProvider(provider);
search.setAdapter(cursorAdapter);
显示了runQuery constraint 的日志语句,但是,在那之后,应用程序崩溃并且我在我的 logcat 中收到此错误:
requesting column name with table name -- <first element of array here>
.....
java.lang.IllegalArugmentException: column <first element of array here> does not exist
单击 logCat 错误行会打开 jar 文件,但其中没有任何一个指向代码中的一行。但是,从一些错误行来看,我认为我使用String[] columnNames 和MatrixCursor 变量的方式有问题。
有人可以帮忙吗?我之前没有使用过带有光标适配器的过滤查询提供程序,所以我对如何继续使用这个非常无能为力。
非常感谢任何帮助。谢谢。
【问题讨论】:
-
@pskink,感谢您的链接。我尝试在链接中实现您的答案,但是遇到了问题。现在编辑我的问题。
-
那么你的问题到底是什么?
-
我似乎无法使
runQuery正常工作。请查看编辑。 -
"from" 参数是列的列表,而不是行
标签: android autocompletetextview