Custom Listview Adapter with filter Android

后端 未结 10 685
北荒
北荒 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 06:42

    First you create the EditText in the xml file and assign an id, eg con_pag_etPesquisa. After that, we will create two lists, where one is the list view and the other to receive the same content but will remain as a backup. Before moving objects to lists first initializes Them the below:

    //Declaring
    
    public EditText etPesquisa;
    
    public ContasPagarAdapter adapterNormal;
    
    public List lstBkp;
    
    public List lstCp;
    
    //Within the onCreate method, type the following:
    
    etPesquisa = (EditText) findViewById(R.id.con_pag_etPesquisa);
    
    etPesquisa.addTextChangedListener(new TextWatcher(){
    
        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
            filter(String.valueOf(cs));
        }
        @Override
        public void beforeTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
    
        // TODO Auto-generated method stub
        }
        @Override
        public void afterTextChanged(Editable e){
    
        }
    
    });
    
    //Before moving objects to lists first initializes them as below:
    
    lstCp = new ArrayList();
    
    lstBkp = new ArrayList();
    
    
    //When you add objects to the main list, repeat the procedure also for bkp list, as follows:
    
    lstCp.add(cp);
    
    lstBkp.add(cp);
    
    
    //Now initializes the adapter and let the listener, as follows:
    
    adapterNormal = new ContasPagarAdapter(ContasPagarActivity.this, lstCp);
    
    lvContasPagar.setAdapter(adapterNormal);
                        lvContasPagar.setOnItemClickListener(verificaClickItemContasPagar(lstCp));
    
    
    //Now create the methods inside actito filter the text entered by the user, as follows:
    
    public void filter(String charText){
    
        charText = charText.toLowerCase();
    
        lstCp.clear();
    
        if (charText.length() == 0){
    
            lstCp.addAll(lstBkp);
    
            appendAddItem(lstBkp);
    
        } 
    
        else {
    
            for (int i = 0; i < lstBkp.size(); i++){
    
                if((lstBkp.get(i).getNome_lancamento() + " - " + String.valueOf(lstBkp.get(i).getCodigo())).toLowerCase().contains(charText)){
    
                    lstCp.add(lstBkp.get(i));
    
                }
    
            }
    
            appendAddItem(lstCp);
        }
    }
    
    private void appendAddItem(final List novaLista){
        runOnUiThread(new Runnable(){
    
            @Override
                public void run(){
                    adapterNormal.notifyDataSetChanged();               
                }
            });
        }
    

提交回复
热议问题