gpt4 book ai didi

android - 如何在保留字符状态的情况下向自动完成 TextView 动态添加建议

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:57:14 26 4
gpt4 key购买 nike

问题描述:

我遇到了 AutoCompleteTextView 的一些问题,我必须在每次按键后显示建议。问题是,建议列表是动态的,就像谷歌的建议功能一样。这意味着应在用户不断输入时添加新建议,并且应显示所有匹配的旧建议。

例如

我写“te”然后它应该显示以前的建议,如“test1”和“test2”以及我将从 Web API 获得的新建议。假设 web api 给我单词“tea”和“tension”。

现在 AutoCompleteTextView 会将“te”作为字符串,并在其下方显示所有四个建议。

这正是我要找的。

看起来很简单,但它表现出一种奇怪的行为。

我正在使用我在全局声明的默认 ArrayAdapter 类实例。

arrayAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,suggestions);
word.setAdapter(arrayAdapter);

建议是ArrayList。

从 WebApi 获得新结果后,我只需调用

arrayAdapter.notifyDataSetChanged();

刷新数据观察器和附加的 View (在我们的例子中是 AutoCompleteListView)。

但它会关闭建议。

当我不使用 notifyDataSetChanged(); 时,无论我输入的是什么字符,它都会显示所有建议。

我按照许多建议使用自定义过滤器进行了尝试,但没有一个有用,因为我无法使用 notifyDataSetChanged()。

我张贴图片以避免混淆。 enter image description here

我很困惑为什么 notifyDataSetChanged(); 它不起作用。我没有使用具有相同 arrayAdapter 实例的任何其他列表引用。真怀疑是不是引用问题。

最佳答案

最简单的方法之一(将代码放在 onCreate 中):

编辑:添加了 wikipedia free opensearch(如果 https://en.wikipedia.org 不起作用,请尝试 http://en.wikipedia.org)

    AutoCompleteTextView actv = new AutoCompleteTextView(this);
actv.setThreshold(1);
String[] from = { "name", "description" };
int[] to = { android.R.id.text1, android.R.id.text2 };
SimpleCursorAdapter a = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, null, from, to, 0);
a.setStringConversionColumn(1);
FilterQueryProvider provider = new FilterQueryProvider() {
@Override
public Cursor runQuery(CharSequence constraint) {
// run in the background thread
Log.d(TAG, "runQuery constraint: " + constraint);
if (constraint == null) {
return null;
}
String[] columnNames = { BaseColumns._ID, "name", "description" };
MatrixCursor c = new MatrixCursor(columnNames);
try {
String urlString = "https://en.wikipedia.org/w/api.php?" +
"action=opensearch&search=" + constraint +
"&limit=8&namespace=0&format=json";
URL url = new URL(urlString);
InputStream stream = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String jsonStr = reader.readLine();
// output ["query", ["n0", "n1", ..], ["d0", "d1", ..]]
JSONArray json = new JSONArray(jsonStr);
JSONArray names = json.getJSONArray(1);
JSONArray descriptions = json.getJSONArray(2);
for (int i = 0; i < names.length(); i++) {
c.newRow().add(i).add(names.getString(i)).add(descriptions.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
};
a.setFilterQueryProvider(provider);
actv.setAdapter(a);
setContentView(actv, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

关于android - 如何在保留字符状态的情况下向自动完成 TextView 动态添加建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19858843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com