Monday, January 14, 2013

ListView Filterable interface - Filter box

In one of previous post, we talked about ListView and custom filter with filterable interface. Some users asked me what happens when user delete chars in the filter box.
In this case it is necessary to modify the method public void onTextChanged so that we can know if we are adding new chars to the filter or we are removing it. The method as two parameters called int before and int count. We can compare it and if:

before < count
we are adding chars and we keep filtering on the same array
before > count
we are deleting chars on the filter and we need to update the array.
In the PlanetAdapter class we need to store the original planet list so that we can go back when we are deleting chars on the filter. So we need to add:
private List<Planet> planetListOrig;
...

public PlanetAdapter(List<Planet> planetList, Context ctx) {
super(ctx, R.layout.img_row_layout, planetList);
this.planetList = planetList;
this.context = ctx;
this.planetListOrig = new ArrayList<Planet>(planetList);
}

and then we need to add this method:
public void resetData() {
planetList = origPlanetList;
}

..and we need to modify the text field in this way:
editTxt.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text ["+s+"] - Start ["+start+"] - Before ["+before+"] - Count ["+count+"]");
if (count < before) {
// We're deleting char so we need to reset the adapter data
aAdpt.resetData();
}

aAdpt.getFilter().filter(s.toString());

}
.....
}



The new code is available here




ListView Filterable interface - Filter box Rating: 4.5 Diposkan Oleh: Unknown

0 comments:

Post a Comment