Flitering a ListView using an input from an EditText in Android.
Hello everyone
In today’s tutorial I will show you how to filter a ListView based on an input from the EditText.
This is really simple we just need to call getFilter().filter(search_string) on the adapter to filter the values from the ListViews.
Just take a look at this example.
Here is the layout file main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/filterText">
<requestFocus></requestFocus>
</EditText>
<ListView android:layout_height="wrap_content" android:id="@+id/android:list"
android:layout_width="fill_parent"></ListView>
</LinearLayout>
Here is the java file named FilterListViewsDemo.java
package pack.coderzheaven;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
public class FilterListViewsDemo extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
getModel());
setListAdapter(adapter);
EditText filterEditText = (EditText) findViewById(R.id.filterText);
filterEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
private List<String> getModel() {
List<String> list = new ArrayList<String>();
list.add("Android");
list.add("Windows7");
list.add("iPhone");
list.add("RIM");
list.add("Symbian");
list.add("Bada");
list.add("MacOSX");
list.add("WindowsXP");
list.add("CoderzHeaven");
return list;
}
}
You can download the full source code from here
Link to this post!

