Custom Listview Adapter with filter Android

后端 未结 10 886
北荒
北荒 2020-11-22 06:07

Please am trying to implement a filter on my listview. But whenever the text change, the list disappears.Please Help Here are my codes. The adapter class.

p         


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 07:04

    I hope it will be helpful for others.

    // put below code (method) in Adapter class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        myList.clear();
        if (charText.length() == 0) {
            myList.addAll(arraylist);
        }
        else
        {
            for (MyBean wp : arraylist) {
                if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                    myList.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }
    

    declare below code in adapter class

    private ArrayList myList;  // for loading main list
    private ArrayList arraylist=null;  // for loading  filter data
    

    below code in adapter Constructor

    this.arraylist = new ArrayList();
        this.arraylist.addAll(myList);
    

    and below code in your activity class

    final EditText searchET = (EditText)findViewById(R.id.search_et);
        // Capture Text in EditText
        searchET.addTextChangedListener(new TextWatcher() {
    
            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
                String text = searchET.getText().toString().toLowerCase(Locale.getDefault());
                adapter.filter(text);
            }
    
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
                // TODO Auto-generated method stub
            }
    
            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                // TODO Auto-generated method stub
            }
        });
    

提交回复
热议问题