Reputation: 151
was hoping you might be able to help me with a problem I've been having. I have a listview that is filtered by an editbox. I figured it would filter, based on the text in the edittext, through any part of the text in the listview. So if I have three items in the listview, "Cupcake", "Donut", "Eclair" and "Froyo", and I typed in "cl", it would't return anything...but if I typed in "ecl", it would return "Eclair". Sorry if I worded it terribly...it's a bit hard to explain. Here's my code:
private EditText ed;
private String lv_arr[]={"Cupcake","Donut","Eclair","Froyo"};
ArrayAdapter<String> arrad;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
ed = (EditText) findViewById(R.id.edit);
ListView list = (ListView) findViewById(R.id.listviewtest);
arrad = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr);
list.setAdapter(arrad);
list.setTextFilterEnabled(true);
ed.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged( CharSequence arg0, int arg1, int arg2, int arg3) {
SearchByName.this.arrad.getFilter().filter(arg0);
}
@Override
public void beforeTextChanged( CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void afterTextChanged( Editable arg0) {
}
});
}
Upvotes: 0
Views: 1151
Reputation: 7350
if you look at the sourcecode for the arrayadapter it will only filter on the first letters of any given word in your list item (so given an item of "eclair donut" it will match on "ecl" or "don" but not "air" or "nut": here is the relevant code from the ArrayAdapter.java
for (int i = 0; i < count; i++) {
final T value = values.get(i);
final String valueText = value.toString().toLowerCase();
// First match against the whole, non-splitted value
if (valueText.startsWith(prefixString)) {
newValues.add(value);
} else {
final String[] words = valueText.split(" ");
final int wordCount = words.length;
for (int k = 0; k < wordCount; k++) {
if (words[k].startsWith(prefixString)) {
newValues.add(value);
break;
}
}
}
}
if you want to filter for any instance of your pattern in the middle of words, you will need to write your own adapter. that implements Filterable
Upvotes: 2