【问题标题】:Android AutoCompleteTextView adapter not updating after ArrayList changeAndroid AutoCompleteTextView 适配器在 ArrayList 更改后未更新
【发布时间】:2015-03-28 11:05:37
【问题描述】:

当用户输入 AutoCompleteTextView 时,我想从 Web 服务中获取一些结果并将它们显示在框中。

为此我在全球范围内声明

ArrayAdapter<String> adapter;
autoCompleteText;
ArrayList<String> searchList;

我把它放在我的 onCreate() 中。 searchList 是一个 ArrayList,我将从 Web 服务中获取结果。 Search() 是我的网络服务搜索。我希望它在用户输入至少 3 个字符后进行搜索,以便我在该字段上使用 TextWatcher。

    adapter = new ArrayAdapter<String>(MyActivity.this
            , android.R.layout.simple_list_item_1, searchList);
    autoCompleteText.setAdapter(adapter);
    autoCompleteText.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            if (s.length() >= 3) {
                new Search().execute(null, null, null);
            }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

来自 Search() 的方法 - 更新我的 searchList 的 AsyncTask 中的 GET 请求

@Override
    protected void onPostExecute(final Void unused) {
        dlg.dismiss();
        if (result != null) {
            try {
                JSONObject myJson = new JSONObject(result.substring(4));

                JSONObject resp = myJson.getJSONObject("response");
                for (Iterator<String> iterator = resp.keys(); iterator.hasNext();) {
                    String key = iterator.next();
                    System.out.println(key + " = " + resp.getString(key));
                    if(! searchList.contains(resp.getString(key)))
                        searchList.add(resp.getString(key));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }
}

我更喜欢使用 ArrayAdapter 而不是 CustomAdapter。有什么想法吗?

【问题讨论】:

标签: android android-arrayadapter


【解决方案1】:

更改列表后尝试在 onPostExecute() 中调用 notifyDataSetChanged()。

【讨论】:

    【解决方案2】:

    这就是我更新AutoCompleteTextView的方式:

    String[] data = terms.toArray(new String[terms.size()]);  
    // terms is a List<String>
    ArrayAdapter<?> adapter = new ArrayAdapter<Object>(activity, android.R.layout.simple_dropdown_item_1line, data);
    keywordField.setAdapter(adapter);  // keywordField is a AutoCompleteTextView
    if(terms.size() < 40) keywordField.setThreshold(1); 
    else keywordField.setThreshold(2);
    

    当然,这是静态的,不处理无线建议,但我也可以建议您在将更改分配给 AutoCompleteTextView 后通知适配器:

    adapter.notifyDataSetChanged();   
    

    【讨论】:

    • 您只是在每篇关于更新适配器的帖子中复制粘贴此链接。我在其他帖子上见过你。尝试提供真正的帮助
    • 对于所有开发人员来说,每个代码永远不会不同。我复制了这个给你一个想法。没有人会为任何人键入每一行。
    • 你在哪里称呼它?
    猜你喜欢
    • 2011-12-26
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 2012-02-23
    相关资源
    最近更新 更多