Monday 8 October 2012

Android ListView with Searchbox Sort items


This article is next step of List Example. Here we have a search box which sorts the list view as when the content matches the list items.
Why do we need this?
Imagine that if we have 2K to 3K items in the listview, It will not be possible to  scrolldown till 2000th item.In this case this will be handy to cut short items.
To start with we add a edittext box and Listview added to LinearLayout.
[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical">
<EditText android:id="@+id/EditText01" android:layout_height="wrap_content" android:layout_width="fill_parent" android:hint="Search"></EditText><ListView android:id="@+id/ListView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" ></ListView>
</LinearLayout>
[/sourcecode]
Have a sample String array that is to loaded as List items.
Create a temporary arraylist that hold the sorted items and Simply add it to the list view on addTextChangedListener() of edit text.
[sourcecode language="java"]
package com.androidpeople;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class searchsort extends Activity {
/** Called when the activity is first created. */
private ListView lv1;
private EditText ed;
private String lv_arr[]={"Android","Cupcake","Donut","Eclairs","AndroidPeople","Froyo",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
ed=(EditText)findViewById(R.id.EditText01);
// By using setAdpater method in listview we an add string array in list.
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<lv_arr.length;i++)
{
if(textlength<=lv_arr[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) lv_arr[i].subSequence(0, textlength)))
{
arr_sort.add(lv_arr[i]);
}
}
}
lv1.setAdapter(new ArrayAdapter<String>(searchsort.this,android.R.layout.simple_list_item_1 , arr_sort));
}
});
}
}
[/sourcecode]
[gallery link="file"]












No comments:

Post a Comment