如何在保留字符状态的情况下向自动完成文本视图动态添加建议 [英] How to dynamically add suggestions to autocompletetextview with preserving character status

查看:27
本文介绍了如何在保留字符状态的情况下向自动完成文本视图动态添加建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题描述:

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

例如

我写了te",然后它应该显示以前的建议,比如test1"&test2"以及我将从 Web API 获得的新建议.假设 web api 给了我单词tea"&紧张".

现在 AutoCompleteTextView 将te"作为字符串,所有四个建议都显示在其下方.

这正是我要找的.

看起来很简单,但表现出奇怪的行为.

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

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

建议是 ArrayList.

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

arrayAdapter.notifyDataSetChanged();

刷新数据观察器和附加的视图(在我们的例子中为 AutoCompleteListView).

但它会关闭建议.

当我不使用 notifyDataSetChanged(); 时,它会显示所有建议,而不管我输入了什么字符.

我尝试了很多建议的自定义过滤器,但没有一个有用,因为我无法使用 notifyDataSetChanged().

我发布了一张图片以避免混淆.

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

解决方案

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

添加维基百科免费开放搜索(如果 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() {@覆盖公共光标运行查询(CharSequence 约束){//在后台线程中运行Log.d(TAG, "runQuery 约束:" + 约束);如果(约束 == 空){返回空;}String[] columnNames = { BaseColumns._ID, "name", "description" };MatrixCursor c = new MatrixCursor(columnNames);尝试 {String urlString = "https://en.wikipedia.org/w/api.php?"+"action=opensearch&search="+ 约束 +"&limit=8&namespace=0&format=json";URL url = 新 URL(urlString);InputStream 流 = url.openStream();BufferedReader reader = new BufferedReader(new InputStreamReader(stream));String jsonStr = reader.readLine();//输出 ["query", ["n0", "n1", ..], ["d0", "d1", ..]]JSONArray json = 新的 JSONArray(jsonStr);JSONArray 名称 = json.getJSONArray(1);JSONArray 描述 = json.getJSONArray(2);for (int i = 0; i 

Problem Description:

I am facing some problem with AutoCompleteTextView where I have to show suggestions after each keypress. Thing is that, list of suggestion is dynamic like google's suggestion feature. It means the new suggestions should be added as user keeps typing in plus all matching old suggestions should be displayed.

For example

I write "te" and then it should display previous suggestions like "test1" & "test2" and the new suggestions that I will get from Web API. Suppose web api gives me word "tea"& "tension ".

Now the AutoCompleteTextView will have "te" as string with all four suggestions showing below it.

This is exactly what I am looking for.

looks simple but it is showing a strange behaviour.

I am using default ArrayAdapter class instance of which I am declaring globally.

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

suggestions is ArrayList.

Upon getting new result from WebApi I simply call

arrayAdapter.notifyDataSetChanged();

to refresh the data observer and views attached with this (in our case AutoCompleteListView).

But it closes suggestions.

When I don't use notifyDataSetChanged(); it is showing all suggestions regardless of characters I have typed.

I tried it with custom filter as many suggested but none of them is helpful as I couldn't use notifyDataSetChanged().

I am posting an image to avoid confusions.

I have a confusion that why notifyDataSetChanged(); its not working. I haven't use any other reference of list with same arrayAdapter instance. I really doubt if it's a reference problem.

解决方案

one of the easiest way of doing that (put the code in onCreate):

EDIT: addied wikipedia free opensearch (if https://en.wikipedia.org doesn't work try 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));

这篇关于如何在保留字符状态的情况下向自动完成文本视图动态添加建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆