过滤后,ListView会显示每个项目两次

时间:2012-03-14 07:42:29

标签: android filter android-listview android-listfragment

我有一个列表,每行包含一个主项和子项。当用户键入搜索edittext时,我使用过滤器刷新列表。 在键入列表中的项目时,会根据键入的字母表显示,但每个项目都会显示两次。 以下是我的代码:

  public class NewReqFragment extends ListFragment 
 {
        ListView newReqList;
    LayoutInflater inflater;
    String[] from = new String[] {"mainrow", "subrow"};
    EditText searchBar = null;
    SimpleAdapter sAdapter =null;

    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);             
    }

    public void onActivityCreated(Bundle savedInstanceState) 
        {
          super.onActivityCreated(savedInstanceState); 

          newReqList = this.getListView();

          searchBar = (EditText)this.getActivity().findViewById(R.id.searchbar);

          List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
          for(int i = 0; i < ListItemStrings.NEWREQTITLES.length; i++)
          {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("mainrow",ListItemStrings.NEWREQTITLES[i]);
                map.put("subrow",ListItemStrings.NEWREQCHILDLIST[i]);
                fillMaps.add(map);
              }         



          sAdapter = new SimpleAdapter (this.getActivity(), fillMaps
                  , R.layout.simple_list_item_checkable_1, 
                  from, new int[] {R.id.text1, R.id.text2}); 
          newReqList.setAdapter(sAdapter);
          searchBar.addTextChangedListener(filterTextWatcher);
    } 

    private TextWatcher filterTextWatcher = new TextWatcher() 
    {

        public void afterTextChanged(Editable s)
        {
        }

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

        public void onTextChanged(CharSequence s, int start, int before,
                int count) 
        {
            sAdapter.getFilter().filter(s);
            sAdapter.notifyDataSetChanged();           
        }


    };

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
     {
        View v = inflater.inflate(R.layout.newreqscrlayout, container,false);
        return v;
     }        
}

任何人都可以帮我找出问题所在吗?

1 个答案:

答案 0 :(得分:0)

我通过制作一个自定义的SimpleAdapter解决了这个问题 我的列表包含Item和Subitem。 SimpleAdapter方法performFiltering()也过滤了子项文本,因此每次添加两个项目。只有获得结果才能执行循环。