Android搜索视图过滤器ListView

20

我已经将搜索过滤器添加到Sherlock Action Bar中的SearchView中。

当我输入“m”时,我希望在下面的列表视图中只显示以M开头的过滤结果。但是现在它显示的结果是随机的。

输入图像描述 输入图像描述

public boolean onQueryTextChange(String newText) {
    Log.i("Nomad", "onQueryTextChange");

    if (TextUtils.isEmpty(newText)) {
        adapter.getFilter().filter("");
        Log.i("Nomad", "onQueryTextChange Empty String");
        placesListView.clearTextFilter();
    } else {
        Log.i("Nomad", "onQueryTextChange " + newText.toString());
        adapter.getFilter().filter(newText.toString());
    }
    return true;
}

public boolean onQueryTextSubmit(String query) {
    Log.i("Nomad", "onQueryTextSubmit");
    return false;
}

public boolean onClose() {
    Log.i("Nomad", "onClose");
    return false;
}
4个回答

21

把这段代码放在你的适配器中:

@Override
public Filter getFilter(){
   return new Filter(){

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
             constraint = constraint.toString().toLowerCase();
             FilterResults result = new FilterResults();

                if (constraint != null && constraint.toString().length() > 0) {
                  List<String> founded = new ArrayList<String>();
                        for(YourListItemType item: origData){
                            if(item.toString().toLowerCase().contains(constraint)){
                                founded.add(item);
                            }
                    }

                        result.values = founded;
                        result.count = founded.size();
                    }else {
                        result.values = origData;
                        result.count = origData.size();
                    }
            return result;


    }
    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
           clear();
           for (String item : (List<String>) results.values) {
                 add(item);
           }
    notifyDataSetChanged();

    }

    }
    }

并且这在你的适配器构造函数内部

public MyAdapter(Context context, int layoutResourceId, String[] places) {
        super(context, layoutResourceId, data);
        this.context = context;

        this.data = Arrays.asList(places);
        this.origData = new ArrayList<String>(this.data);

 }

this.data = Arrays.asList(places); - 这样就可以了。 - Artem Zelinskiy
1
你应该在适配器方法中重写add(),并使用你的类型。 - Artem Zelinskiy
1
如果您使用“extends ArrayAdapter<YourItemType>”对ArrayAdapter进行参数化,则不需要覆盖ArrayAdapter中的add()方法。此外,除非您删除所有字符,否则您的代码在过滤框中删除字符时无法正常工作。因此,我的建议是使用“for (YourListItemType item: origData)”而不是“for (YourListItemType item: data)”,因为data会被过滤过程修改。 - arne.jans
@arne.jans 谢谢你的建议,我稍微修改了一下我的代码。 - Artem Zelinskiy
我想使用这段代码,但是你回答中的“origData”是什么? - uniruddh
显示剩余9条评论

6
从适配器中获取筛选器并根据搜索视图字段中更改的字符串在查询更改时进行过滤。
searchView.setOnQueryTextListener(new OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            getListAdapter().getFilter().filter(newText);
            return true;
        }
    });

当列表被清空而不是被过滤时,我该怎么办? - JorgeAmVF
1
我猜这取决于你想要实现的效果,也许在过滤出要显示的内容之前先隐藏它。 - Ivor
什么是getListAdapter()?我有ArrayList<String> array_list = new ArrayList<>(); ArrayAdapter arrayAdapter = new ArrayAdapter(getContext(), android.R.layout.simple_list_item_1, array_list);,当我用arrayAdapter替换getListAdapter()时,我得到了这个错误non static method cannot be referenced from a static context。真的希望你能帮忙,我一直在寻找在片段中对ListView进行简单搜索的方法,但没有成功。 - M J

1

将元素添加到listview_arr中,其余代码如下...:-

    listview_arr = new String[listview_array_location.length];
    listview_arr = listview_array;

    setListAdapter(new bsAdapter(this));


    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)
        {
            /*Log.d("count","count==>"+s.length());

                if(((s.length()-temp)%4)==0)
                {
                    Log.d("in if","if in if"+(s.length()-temp));
                    et.setText(et.getText().toString()+" ");
                    int position = et.getText().toString().length();
                    Editable etext = et.getText();
                    Selection.setSelection(etext, position);
                    temp++;
                }*/

            Log.d("count","count==>"+s);
            textlength = et.getText().length();
            array_sort.clear();
            for (int i = 0; i < listview_array_location.length; i++)
            {
                if (textlength <= listview_array_location[i].length())
                {
                    if(et.getText().toString().equalsIgnoreCase((String)listview_array_location[i].subSequence(0,textlength)))
                    {
                        array_sort.add(listview_array[i]);
                    }
                  }
            }
            AppendList(array_sort);
        }
    });
}

public void AppendList(ArrayList<String> str)
{
    listview_arr = new String[str.size()];
    listview_arr = str.toArray(listview_arr);

    setListAdapter(new bsAdapter(this));
}

public class bsAdapter extends BaseAdapter
{
    Activity cntx;
    public bsAdapter(Activity context)
    {
        // TODO Auto-generated constructor stub
        this.cntx=context;

    }

    public int getCount()
    {
        // TODO Auto-generated method stub
        return listview_arr.length;
    }

    public Object getItem(int position)
    {
        // TODO Auto-generated method stub
        return listview_arr[position];
    }

    public long getItemId(int position)
    {
        // TODO Auto-generated method stub
        return listview_array.length;
    }

    public View getView(final int position, View convertView, ViewGroup parent)
    {
        View row=null;

        LayoutInflater inflater=cntx.getLayoutInflater();
        row=inflater.inflate(R.layout.search_list_item, null);

        TextView tv=(TextView)row.findViewById(R.id.title);
        Button Btn01=(Button)row.findViewById(R.id.Btn01);
        Button Btn02=(Button)row.findViewById(R.id.Btn02);

        tv.setText(listview_arr[position]);

        Btn01.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                Toast.makeText(SearchUser.this, "Button 1 "+listview_arr[position], Toast.LENGTH_SHORT).show();
                  int color = PreferenceManager.getDefaultSharedPreferences(
                          SearchUser.this).getInt(COLOR_PREFERENCE_KEY, Color.WHITE);
                  new ColorPickerDialog(SearchUser.this, SearchUser.this, color).show();
            }
         });

        Btn02.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v) 
            {
                Toast.makeText(SearchUser.this, "Button 2 "+listview_arr[position], Toast.LENGTH_SHORT).show();
            }
         });

    return row;
    }
}

0

你可以简单地浏览一下示例。它非常容易集成到你的应用程序中。

这里是使用数组和addTextChangedListener为EditText编写的逻辑。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接