在ListFragment中更改文本时筛选列表

时间:2014-04-18 14:36:43

标签: android list android-listfragment

我有一个扩展ListFragment的片段。这个片段还包含一个EditText元素,我希望在文本更改时过滤列表。

我想到了以下代码:

    EditText inputSearch = (EditText) getView().findViewById(R.id.inputGroupSearch);
    inputSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2,
                int arg3) {
            // When user changed the Text
            getListAdapter().getFilter().filter(cs);
        }});

但是,某种程度上getListAdapter()没有“getFilter()”方法。 我希望能有更好的解决方法。

谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个:

 lv.setAdapter(new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_list_item_activated_1, list.TERM));
   lv.setTextFilterEnabled(true); 
   et.addTextChangedListener(new TextWatcher()
   {
        public void afterTextChanged(Editable s)
    {
      // Abstract Method of TextWatcher Interface.
    }
    public void beforeTextChanged(CharSequence s,
    int start, int count, int after)
    {
    // Abstract Method of TextWatcher Interface.
    }
    public void onTextChanged(CharSequence s,int start, int before, int count)
    {
    textlength = et.getText().length();
    array_sort.clear();
    for (int i = 0; i < words.length; i++)
    {
       if (textlength <= words[i].length())
       {
          if(et.getText().toString().equalsIgnoreCase((String)words[i].subSequence(0, textlength)))
               {
                 array_sort.add(words[i]);
               }
       }
    }
    lv.setAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_activated_1, array_sort));
  }
   });

答案 1 :(得分:0)

将getListAdapter返回的适配器Typecast引入您自己的自定义适配器

filerText = (EditText) view.findViewById(R.id.filerText);
filerText.addTextChangedListener(new TextWatcher() {   
    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        YourCustomAdapter adapter = (YourCustomAdapter)getListAdapter();
        adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});