如何过滤ListView中的第二行?

时间:2018-04-15 17:50:53

标签: android listview

我有一个包含2行的ListView,上面有一个EditText,用于搜索。 现在我想过滤这个listView中的第二行。 怎么做?

ArrayList<HashMap<String, String>> data;
        String[] titleArray,subItemArray;
        data = new ArrayList<HashMap<String, String>>();

        for(int i=0;i<list1.size();i++){
            HashMap<String,String> datum = new HashMap<String, String>();

            datum.put("items", list1.get(i));
            datum.put("sumItems", list2.get(i));
            data.add(datum);
        }
        SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"RouterName", "RouterIP"}, new int[] {android.R.id.text1, android.R.id.text2});
        lst.setAdapter(adapter);
        /**
         * Enabling Search Filter
         * */
        inputSearch.addTextChangedListener(new TextWatcher() {

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

            }

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

            @Override
            public void afterTextChanged(Editable s) {

            }

1 个答案:

答案 0 :(得分:0)

通过使用Filterable接口

实现适配器来编写自定义过滤器
ItemFilter mFilter = new ItemFilter();

@Override
public Filter getFilter() {

    return mFilter;

}



private class ItemFilter extends Filter {

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {


        String filterString = constraint.toString().toLowerCase();


        FilterResults results = new FilterResults();


        final List<String> list = originalData;


        int count = list.size();

        final ArrayList<String> nlist = new ArrayList<String>(count);


        String filterableString ;


        for (int i = 0; i < count; i++) {

            filterableString = list.get(i);

            if (filterableString.toLowerCase().contains(filterString)) {

                nlist.add(filterableString);

            }

        }


        results.values = nlist;

        results.count = nlist.size();


        return results;

    }


    @SuppressWarnings("unchecked")

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {

        filteredData = (ArrayList<String>) results.values;

        notifyDataSetChanged();

    }


}