Initially design a xml file as show below:
<?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:id="@+id/EtBrandName" android:layout_height="wrap_content"
android:layout_width="fill_parent" android:hint="Search">
</EditText>
<ListView android:id="@+id/lvItems"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Then write the following code in your activity:-
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 LSearch extends Activity {
private ListView lv1;
private EditText ed;
private String lv_arr[]={"Android","Cupcake", "Donut","Eclairs"," AndroidPeople","Froyo","Apple" ,"Samsung","Storeage","Sony"};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState);
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>(LSearch. this,android.R.layout.simple_ list_item_1 , arr_sort));
}
});
}
}
your output will look as shown below:
Instead of ArrayAdapter can we use simpleAdapter for this example,pls explain anyone how to use simpleAdapter for this example.
ReplyDeleteya we can use any adapter
ReplyDelete