androidandroid-listviewtextviewkeylistenerandroid-event

how to get the text of a edit text when after pressing a key


I want to search a ListView when user types a text in a EditText. after pressing a key I need to get the typed part of text to begin the search. so is there any method I can use?? simple help is highly appreciated.


Solution

  • If you're using an ArrayAdapter to populate your ListView, then do it like this:

       edittext.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
        }
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
    
                yourAdapter.getFilter().filter(s);
        }
    
        @Override
        public void afterTextChanged(Editable s) {
    
        }
    });
    

    Add a TextWatch to your EditText and user the filter in your adapter to show the results that match. To highlight the matched result , you may want to use SpannableString for "prettyfying" it.

    From ArrayAdapter.getFilter():

    Returns a filter that can be used to constrain data with a filtering pattern.

    This method is usually implemented by Adapter classes.