为何无法动态更新AutoCompleteTextView?

我使用ArrayList和ArrayAdapter记录AutoCompleteTextView的内容,并且我想在修改列表后动态刷新AutoCompleteTextView.列表的修改在webviewClient中触发.

但是,我的代码不起作用.仅当重新加载整个活动时,才可以更新AutoCompleteTextView.根本没有动态更新.谁能帮助我找出问题所在?

    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, mHistory); //mHistory is the list of data
    adapter.setNotifyOnChange(true);
    mEditText1.setAdapter(adapter); //mEditText1 is the AutoCompleteTextView

    mWebView1.setWebViewClient(new WebViewClient() {

        public void onPageFinished(WebView view, String url){
            super.onPageFinished(view, url);

            if (!mHistory.contains(mWebView1.getUrl())){
                mHistory.add(mWebView1.getUrl());
                writeList(view.getContext(), mHistory, "history");  //this is to store the list elsewhere
            }
            adapter.notifyDataSetChanged();

        }

    });         

解决方法:

我想建议您不要尝试修改列表mHistory,而应使用add(),clear()等来修改ArrayAdapter.

adapter.add(mWebView1.getUrl());

另外,如果那没有帮助,您可以尝试创建自己的自定义适配器,而不是默认的ArrayAdapter.您可以通过使用公共功能call强制过滤.自定义适配器可能是这样的:

public class CustomArrayAdapter extends ArrayAdapter<String> implements
        Filterable {
    private List<String> list;
    private CustomFilter customFilter;

    public CustomArrayAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
        list = new ArrayList<String>();
    }

    @Override
    public void add(String object) {
        list.add(object);
        notifyDataSetChanged();
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public String getItem(int position) {
        return list.get(position);
    }

    @Override
    public CustomFilter getFilter() {
        if (customFilter == null) {
            customFilter = new CustomFilter();
        }
        return customFilter;
    }

    public void callFiltering(String term) {
        customFilter.performFiltering(term);
    }

    private class CustomFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            if (constraint != null) {
                results.values = list;
                results.count = list.size();
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
            if (results != null && results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }

    }

}
上一篇:Python,Zope组件体系结构,注册适配器


下一篇:java-RecycleView分页末尾没有添加新项目?