Tuesday, December 13, 2011

Android TextWatcher(auto-complete-text-view) example

We often require a ListView with search option. Here is an example of a ListView with a TextEdit on top. The target of this program is to update the list items as user types into the TextEdit box.

Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/item_top_wrapper" android:background="#991A1111"
android:paddingLeft="2dip" android:paddingRight="2dip"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:focusable="true"
android:focusableInTouchMode="true">
<EditText android:id="@+id/search_string"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:hint="Search Key"
android:singleLine="true" />
</LinearLayout>

<ListView
android:id="@+id/itemList"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/item_top_wrapper"
android:background="#55E0FFFF"
android:cacheColorHint="#00000000"/>

</RelativeLayout>

Activity Code:
ListView itemListView = (ListView)findViewById(R.id.itemList);
TextView textView = (TextView)findViewById(R.id.search_string);
ArrayAdapter<String> autoCompleteAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);
// This is so I don't have to manually sync whenever changed
autoCompleteAdapter.setNotifyOnChange(true);

itemListView.setAdapter(autoCompleteAdapter);

final TextWatcher textChecker = new TextWatcher() {

public void afterTextChanged(Editable s) {
textView.setEnabled(true);
}

public void beforeTextChanged(CharSequence s, int start, int count, int after) {
textView.setEnabled(false);
}

public void onTextChanged(CharSequence s, int start, int before, int count) {
autoCompleteAdapter.clear();
for (int i=1; i < nameArr.length; i++) {
if(nameArr[i].contains(s.toString()))
autoCompleteAdapter.add((String) nameArr[i]);
}
}
};
textView.addTextChangedListener(textChecker);

No comments: