Android ListView:如何更改列表的内容?

时间:2011-11-02 16:03:31

标签: android android-listview

我有一个ListView,其想法是当用户输入时只显示给出的唯一字符串 用户将从用户写的开始。

如果每个Android设备都有一个物理键盘,我可以用这个简单的代码实现这个目标:

      ListView lv = getListView();
      lv.setTextFilterEnabled(true);

但是你可能知道像三星galaxi S这样的设备没有物理键盘。

我所做的是创建一个只有EditText的简单布局文件,我使用了addHeaderView方法,所以我现在在列表上方有一个EditText(用户可以输入)。 我想使用addTextChangedListener,以便我可以对用户输入的内容做出反应。

问题是如何更改显示以便它只显示我想要的字符串(我没有找到这些字符串的问题,问题是如何更新当前的显示) 或者,如果有另一种解决方案可以克服某些设备没有物理键盘的事实,那也很好。

2 个答案:

答案 0 :(得分:0)

一种解决方案可能是在AsyncTask中过滤显示的列表,然后更新适配器中的列表。通过notifyDataSetChanged,然后更新列表以仅显示所需的项目。 这可能不是一个优雅的解决方案,但它对我有用。

编辑: 这应该工作

   void setTextChangedListenerToSearchBox(EditText etFilter) {

    if (etFilter == null)
        return;

    etFilter.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
            // nothing done here
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // nothing done here
        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if (s.toString() != null) {
                searchupdate(s.toString());
            }
        }

    });
}


void searchupdate(String s)
{
    final List<String> currentItems = new ArrayList<String>(yourCurrentlyDisplayedItems);

    (new AsyncTask<String,Void,List<String>>() {

        @Override
        protected List<String> doInBackground(String... params)
        {
            List<String> listitems = new ArrayList<String>();

            for(String item : currentItems) {
                if(item.contains(params[0])) {
                    listitems.add(item);
                }
            }
            return listitems;
        }

        @Override
        protected void onPostExecute(List<String> result)
        {
            adapter.clear();
            adapter.addAll(result);
            adapter.notifyDataSetChanged();
        }

    }).execute(s);
}

答案 1 :(得分:0)

我确信你想要实现类似的东西:ListView应该根据用户输入的值进行更新,如果是这种情况,那么这里是一个例子:Android ListView with Searchbox Sort items