开发者

Filter ListView Based on user input's in Android?

I need to filter List View as per the user's input in the Edit Text Field.If the user Enter the letter 'a' i need to show the list items starts with 'a'.Can anyone give some ideas to me to solve this ? Thanks in advance?

void searchEngine(final String[] strArr){
      LinearLayout llay=new LinearLayout(this);
      llay.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));        
      llay.setOrientation(LinearLayout.VERTICAL);

      final ListView lv=new ListView(this);        
      lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_checked, strArr));      


      final EditText ed=new EditText(searcher.this);
      ed.setWidth(80);
      ed.setOnEditorActionListener(new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            // TODO Auto-generated method stub
             lv.setTextFilterEnabled(true);
             String strfilter=ed.getText().toString();
             lv.setFilterText(strfilter);

            return false;
        }
    });

      llay.addView(ed);
  开发者_运维知识库    llay.addView(lv);


    setContentView(llay);

}


onEditorAction is called not after input one character, but after some actions like pressing Enter for example. Try to use TextWatcher instead.

ed.addTextChangedListener(new TextWatcher() {
    @Override
    public void afterTextChanged(Editable s) {
        lv.setFilterText(s.toString());
    }

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

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) { }
});


This is what you are looking for: search dialog. Fill the suggestions for it with the items in the ListView, while you type in it it will get filtered. It is better to filter the search dialog instead of filtering the list view.

If you want to have only 1 item at the end in the list view, take the selected (clicked) item in the search dialog, and remove all items in the listview that aren't equal to it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜