¿Cómo puedo filtrar la vista de lista usando baseadapter

Estoy intentando filtrar la vista de lista, pero el método getfilter no funciona,

aquí está el código:

@Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mHistoryAdapter.getFilter().filter(s); } 

he agregado el método en baseadapter también

 public Filter getFilter() { return null; } 

pero no funciona … podría ayudarme alguien .. @ Gracias

MainActivity.java

 public class MainActivity extends Activity { private ListView mListView; private CustomAdapter mCustomAdapter; private EditText mEditText; private ArrayList _Contacts = new ArrayList(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); for (int i = 0; i < 100; i++) { Contacts contacts = new Contacts(); contacts.setId(""+i); contacts.setName("Name "+i); _Contacts.add(contacts); } mListView = (ListView) findViewById(R.id.listView1); mEditText = (EditText) findViewById(R.id.editText1); mCustomAdapter = new CustomAdapter(MainActivity.this, _Contacts); mListView.setAdapter(mCustomAdapter); mEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { mCustomAdapter.getFilter().filter(arg0); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable arg0) { } }); } } 

CustomAdapter.java

 public class CustomAdapter extends BaseAdapter implements Filterable{ private ArrayList _Contacts; private Activity context; private LayoutInflater inflater; private ValueFilter valueFilter; private ArrayList mStringFilterList; public CustomAdapter(Activity context, ArrayList _Contacts) { super(); this.context = context; this._Contacts = _Contacts; mStringFilterList = _Contacts; this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); getFilter(); } @Override public int getCount() { return _Contacts.size(); } @Override public Object getItem(int position) { return _Contacts.get(position).getName(); } @Override public long getItemId(int position) { return 0; } public class ViewHolder { TextView tname, tplace; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.activity_main, null); holder.tname = (TextView) convertView.findViewById(R.id.textView1); holder.tplace = (TextView) convertView.findViewById(R.id.textView2); convertView.setTag(holder); } else holder = (ViewHolder) convertView.getTag(); holder.tname.setText("" + _Contacts.get(position).getName()); holder.tplace.setText("" + "" + _Contacts.get(position).getId()); return convertView; } @Override public Filter getFilter() { if(valueFilter==null) { valueFilter=new ValueFilter(); } return valueFilter; } private class ValueFilter extends Filter { //Invoked in a worker thread to filter the data according to the constraint. @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults results=new FilterResults(); if(constraint!=null && constraint.length()>0){ ArrayList filterList=new ArrayList(); for(int i=0;i) results.values; notifyDataSetChanged(); } } } 

Contactos.java

 public class Contacts { private String name; private String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } } 

main.xml

        

activity_main.xml

    

Este es un código de proyecto de muestra. Usa este código, esto realmente te ayudará

Aqui tienes. Un baseadapter simple (sin reciclaje de vista) que mostrará y filtrará una lista de algún objeto arbitrario personalizado. En este ejemplo Object.name es el campo que usaremos para filtrar.

1) En su actividad, (o) donde crea su ListView , habilite el filtrado de texto:

 class MyObject { public String name; } List myData = ArrayList<>(); listview.setTextFilterEnabled(true); 

2) Como ya observó, en un textwatcher de Edittext, active el filtro en el ListAdapter :

 public void onTextChanged(CharSequence s, int start, int before, int count) { listadapter.getFilter().filter(s); } 

3) en su baseadapter, implement Filterable Filterable. Y almacene dos copias de los datos, uno original y otro filtrado. Asegúrese de acceder a los datos filtrados en todo el BaseAdapter, no a los datos no filtrados

 public class FilterableListAdapterExample extends BaseAdapter implements Filterable { private List mData; //the original data private List mDataFiltered;//the filtered data private LayoutInflater mLayoutInflater; public FilterableListAdapterExample(Context context, List data) { mData = data; mDataFiltered=data; mLayoutInflater = LayoutInflater.from(context); } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView= mLayoutInflater.inflate(R.layout.listview_item, null); TextView textview=(TextView)convertView.findViewById(R.id.listitem_textview); //note: we access mDataFiltered, not mData textview.setText(mDataFiltered.get(position).name); return convertView; } @Override public long getItemId(int position) { return position; } @Override public int getCount() { return mDataFiltered.size(); } @Override public Filter getFilter() { return new Filter() { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults results = new FilterResults(); if (constraint == null || constraint.length() == 0) { //no constraint given, just return all the data. (no search) results.count = mData.size(); results.values = mData; } else {//do the search List resultsData = new ArrayList<>(); String searchStr = constraint.toString().toUpperCase(); for (MyObject o : mData) if (o.name.toUpperCase().startsWith(searchStr)) resultsData.add(o); results.count = resultsData.size(); results.values = resultsData; } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { mDataFiltered = (ArrayList) results.values; notifyDataSetChanged(); } }; } 

}

Intenta seguir el código que puede ser útil para ti:

 public class MainActivity extends ListActivity { private List list = new ArrayList(); List mOriginalValues; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final MyAdapter adapter = new MyAdapter(this, getModel()); setListAdapter(adapter); EditText filterEditText = (EditText) findViewById(R.id.filterText); // Add Text Change Listener to EditText filterEditText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Call back the Adapter with current character to Filter 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 getModel() { list.add("Linux"); list.add("Windows7"); list.add("Suse"); list.add("Eclipse"); list.add("Ubuntu"); list.add("Solaris"); list.add("Android"); list.add("iPhone"); list.add("Windows XP"); return list; } // Adapter Class public class MyAdapter extends BaseAdapter implements Filterable { List arrayList; List mOriginalValues; // Original Values LayoutInflater inflater; public MyAdapter(Context context, List arrayList) { this.arrayList = arrayList; inflater = LayoutInflater.from(context); } @Override public int getCount() { return arrayList.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } private class ViewHolder { TextView textView; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.row, null); holder.textView = (TextView) convertView .findViewById(R.id.listTxt); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.textView.setText(arrayList.get(position)); return convertView; } @Override public Filter getFilter() { Filter filter = new Filter() { @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint,FilterResults results) { arrayList = (List) results.values; // has the filtered values notifyDataSetChanged(); // notifies the data with new filtered values } @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values List FilteredArrList = new ArrayList(); if (mOriginalValues == null) { System.out.println(""); mOriginalValues = new ArrayList(arrayList); // saves the original data in mOriginalValues } /******** * * If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values * else does the Filtering and returns FilteredArrList(Filtered) * ********/ if (constraint == null || constraint.length() == 0) { // set the Original result to return results.count = mOriginalValues.size(); results.values = mOriginalValues; } else { constraint = constraint.toString().toLowerCase(); for (int i = 0; i < mOriginalValues.size(); i++) { String data = mOriginalValues.get(i); if (data.toLowerCase().startsWith(constraint.toString())) { FilteredArrList.add(data); } } // set the Filtered result to return results.count = FilteredArrList.size(); results.values = FilteredArrList; } return results; } }; return filter; } } } 

Creo que no hay necesidad del método getfilter () aquí

 ArrayList data; . . . Collections.sort(data, new Comparator() { @Override public int compare(YourDataModel data1, YourDataModel data2) { if( data1.getDistance() < data2.getDistance() ) return 1; else return 0; } }); . . . ListView lvData = (ListView) findViewById(R.id.listview1); MyCustomAdapter adapter = new MyCustomAdapter(this, R.layout.listview_item_row, data); lvData.setAdapter(adapter); 

y use el método notifydatachange cada vez que quiera actualizarlo