Tuesday, February 14, 2012

Filtering text for Soft Keyboard in android?

Lets say you want to show a list of available options as someone types. Filtering your list based the text of the TextEdit works fine until the user uses a soft keypad. The soft keypad buffers the characters so you do not get them as they are typed. To get around this issue, you can have your view implement the TextWatcher.

public class LocationDialog extends Dialog implements TextWatcher

Then you must implement the following methods.


@Override
public void afterTextChanged(Editable s)
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)

The one we care about is afterTextChange. Here is an example of filtering text to display available options for both the keypad and soft keypad.

public void filter(String curText){
    strings.clear();
    for(int i=0; i < allMaps.size(); i++){
        if(allStrings.get(i).toUpperCase().startsWith(curText)){
            strrings.add(allStrings.get(i));
        }
    }
    stringsAdapter.notifyDataSetChanged();
}

@Override
public void afterTextChanged(Editable s) {
    filter(s.toString().toUpperCase());
}

No comments:

Post a Comment