Impostare un filtro su BaseAdapater in Android

Mattepuffo's logo
Impostare un filtro su BaseAdapater in Android

Impostare un filtro su BaseAdapater in Android

In un precedente articolo abbiamo visto come implementare un nostro BaseAdapter.

Oggi completiamo il tutto impostando anche un filtro.

Per farlo dobbiamo implementare l'interfaccia Filterable, e fare l'Override del metodo getFilter.

Questa la classe:

public class LazyAdapter extends BaseAdapter implements Filterable {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private ArrayList<HashMap<String, String>> originalData;
    private static LayoutInflater inflater = null;

    public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data = d;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (convertView == null) {
            vi = inflater.inflate(R.layout.list_layout, null);
        }
        TextView txtCodice = (TextView) vi.findViewById(R.id.txt_codice);
        TextView txtRagSoc = (TextView) vi.findViewById(R.id.txt_ragsoc);
        HashMap<String, String> cliente = new HashMap<String, String>();
        cliente = data.get(position);
        txtCodice.setText(cliente.get("CODICE"));
        txtRagSoc.setText(cliente.get("RAGSOC"));
        return vi;
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                data = (ArrayList<HashMap<String, String>>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                ArrayList<HashMap<String, String>> fData = new ArrayList<HashMap<String, String>>();
                if (originalData == null) {
                    originalData = new ArrayList<HashMap<String, String>>(data);
                }
                if (constraint == null || constraint.length() == 0) {
                    results.count = originalData.size();
                    results.values = originalData;
                } else {
                    constraint = constraint.toString().toLowerCase();
                    for (int i = 0; i < originalData.size(); i++) {
                        HashMap<String, String> strMap = originalData.get(i);
                        if (strMap.get("CODICE").startsWith(
                                constraint.toString())
                                || strMap.get("RAGSOC")
                                .toLowerCase(Locale.getDefault())
                                .startsWith(constraint.toString())) {
                            fData.add(strMap);
                        }
                    }
                    results.count = fData.size();
                    results.values = fData;
                }
                return results;
            }
        };
        return filter;
    }

}

In sostanza, man mano che scriviamo nella EditText che vedremo dopo, controlliamo se il risultato corrisponde a qualcosa nella lista; quando vengono trovati i risultati, vengono "eliminati" gli altri.

Per usarlo nell costruttore della nostra Activity avremmo una cosa del genere:

        txtSearch = (EditText) findViewById(R.id.txt_search);
        txtSearch.addTextChangedListener(new TextWatcher() {

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

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

In pratica richiamiamo il filtro del nostro adapter.

Enjoy!


Condividi

Commentami!