Sunday 31 March 2013

Searching Text in Listview


TextswitcherdemoActivity.java


public class TextswitcherdemoActivity extends Activity {

 ArrayAdapter<String> dataAdapter = null;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  //Generate list View from ArrayList
  displayListView();

 }

 private void displayListView() {

  //Array list of countries
  List<String> countryList = new ArrayList<String>();
  countryList.add("Aruba");
  countryList.add("Anguilla");
  countryList.add("Netherlands Antilles");
  countryList.add("Antigua and Barbuda");
  countryList.add("Bahamas");
  countryList.add("Belize");
  countryList.add("Bermuda");
  countryList.add("Barbados");
  countryList.add("Canada");
  countryList.add("Costa Rica");
  countryList.add("Cuba");
  countryList.add("Cayman Islands");
  countryList.add("Dominica");
  countryList.add("Dominican Republic");
  countryList.add("Guadeloupe");
  countryList.add("Grenada");
  countryList.add("Greenland");
  countryList.add("Guatemala");
  countryList.add("Honduras");
  countryList.add("Haiti");
  countryList.add("Jamaica");

  //create an ArrayAdaptar from the String Array
  dataAdapter = new ArrayAdapter<String>(this,
    R.layout.country_list, countryList);
  ListView listView = (ListView) findViewById(R.id.listView1);
  // Assign adapter to ListView
  listView.setAdapter(dataAdapter);

  //enables filtering for the contents of the given ListView
  listView.setTextFilterEnabled(true);

  listView.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    // When clicked, show a toast with the TextView text
    Toast.makeText(getApplicationContext(),
     ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
   }
  });

  EditText myFilter = (EditText) findViewById(R.id.myFilter);
  myFilter.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) {
   dataAdapter.getFilter().filter(s.toString());
  }
  });
 }  
}


Click below link for download project
https://sites.google.com/site/httpnepstareblogspotin/http-nepstare-blogspot-in/Textswitcherdemo.rar?attredirects=0&d=1

No comments:

Post a Comment