web-dev-qa-db-ja.com

arrayadapterでListViewをフィルタリングする

Arrayadapterでリストビューをフィルタリングしようとしています。 arraydapterパラメーターはString [] []です。問題は、何かが起こるということです。フィルタインターフェイスをオーバーライドする必要がありますか?その場合、誰かがいくつかのヒントを提供できますか?

フィルタリングしようとしている配列のすべての位置は次のようになります

 galleryValues[0][0] -> "tiulo"
              [0][1] -> "desc"
              [0][2] -> "etc"

私はそれをフィルタリングしようとしました:

lstContinente = (ListView)findViewById(R.id.list);
lstContinente.setTextFilterEnabled(true);
adapter = new PortaitArrayAdapter(cx,galleryValues);   
lstContinente.setAdapter(adapter);

ed_busqueda.addTextChangedListener(new TextWatcher() {           
    public void afterTextChanged(Editable s) {}      
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    // TODO Auto-generated method stub       
}        
public void onTextChanged(CharSequence s, int start, int before, int count) {
    adapter.getFilter().filter(s.toString());
    adapter.notifyDataSetChanged();                 
}        
});

アダプターコード:

public class PortaitArrayAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final String[][] values;
    private List<Imagen> imagenes = null;
    private LayoutInflater mInflater;
    public ImageLoader imageLoader;     


    public PortaitArrayAdapter(Context context, String[][] values) {
        super(context, R.layout.gallery_row);
        this.context = context;
        this.values = values;
        mInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        imagenes = new ArrayList<Imagen>();
        for (int i = 0; i < 20; i++) imagenes.add(new Imagen());
        Bitmap def = BitmapFactory.decodeResource(this.context.getResources(),R.drawable.ic_launcher);
        imageLoader=new ImageLoader(this.context,def, imagenes);
    }



    @Override
    public int getCount (){
        return this.values.length;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();

            convertView =  mInflater.inflate(R.layout.gallery_row, parent, false);
            holder.txtTitulo = (TextView) convertView.findViewById(R.id.txt_gallery_titulo);
            holder.txtDesc = (TextView) convertView.findViewById(R.id.txt_gallery_desc);
            holder.txtFecha = (TextView) convertView.findViewById(R.id.txt_gallery_fecha);
            holder.txtEst = (TextView) convertView.findViewById(R.id.txt_gallery_est);
            holder.imageView    = (ImageView)convertView.findViewById(R.id.lst_img_gallery);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        /*LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.gallery_row, parent, false);*/

        //ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);


        Bitmap bmp;
        Log.v("Position --> ",String.valueOf(position));
        try {
            byte b[] = imagenes.get(position).getImageData();
            if (b != null) {
                bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
                if (bmp != null) holder.imageView.setImageBitmap(bmp);
            } else {

                String urlBase = galleryValues[position][0].substring(0, galleryValues[position][0].lastIndexOf("/")+1);
               String urlToEncode = galleryValues[position][0].substring(galleryValues[position][0].lastIndexOf("/")+1, galleryValues[position][0].length());

               urlToEncode = URLEncoder.encode(urlToEncode,"UTF-8");

               String url = urlBase.concat(urlToEncode);

               url = url.replace("+", "%20");
               Log.v("UrlFinal --> ",url);

                imageLoader.DisplayImage(String.valueOf(position),url,act,holder.imageView, position,null);
            }

        } catch (Exception e) {
            Log.e(this.getClass().getName(),"Exception en pos = " + position + " error:" + e.getMessage());
            e.printStackTrace();
        }


        holder.txtTitulo.setText(galleryValues[position][1] + ", " + galleryValues[position][2]);

        String[] dates = galleryValues[position][4].split("/");  
        String date = dates [1] + "/" + dates[0] + "/" + dates[2];
        Date d1 = new Date(date);
        DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
        holder.txtDesc.setText(galleryValues[position][3]);

        holder.txtFecha.setText(df.format(d1));
        holder.txtEst.setText(getText(R.string.num_fotos_gallery) + galleryValues[position][5] + " - " + getText(R.string.num_videos_gallery) + galleryValues[position][6] + " - " + getText(R.string.num_exp_gallery) + galleryValues[position][7]);

        return convertView;
    }

}

private static class ViewHolder {
    TextView txtTitulo;
    TextView txtDesc;
    TextView txtFecha;
    TextView txtEst;
    ImageView imageView;
}
17
user1159489

文字列配列をArrayListに変換してAdapterに渡し、以下のコードを使用するか、_String[]_で以下のコードを変更します。

FilterableAdapterクラスとOverride getFilter()に実装する必要があります

チェックアウト this カスタムAdapterをフィルタリングするための完全な例。

_public class ListFilterActivity extends ListActivity {

    private List<String> list = new ArrayList<String>();
    List<String> 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<String> 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<String> arrayList;
    List<String> mOriginalValues; // Original Values
    LayoutInflater inflater;

    public MyAdapter(Context context, List<String> 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.textview);
            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<String>) 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<String> FilteredArrList = new ArrayList<String>();

                if (mOriginalValues == null) {
                    mOriginalValues = new ArrayList<String>(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;
    }
}
_
26
Venky

ここカスタムアダプタを使用してlistViewデータをフィルタリングする方法のコードについて説明します
それは本当にあなたを助けます

ListViewAdapter.Java

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context mContext;
    LayoutInflater inflater;
    public List<AllFoodItem> allFoodItemlist;
    public ArrayList<AllFoodItem> arraylist;

    public ListViewAdapter(Context context, List<AllFoodItem> allFoodItemlist) {
        mContext = context;
        this.allFoodItemlist = allFoodItemlist;
        inflater = LayoutInflater.from(mContext);
        this.arraylist = new ArrayList<AllFoodItem>();
        this.arraylist.addAll(allFoodItemlist);
    }
    @Override
    public int getCount() {
        return allFoodItemlist.size();
    }

    @Override
    public AllFoodItem getItem(int position) {
        return allFoodItemlist.get(position);
    }

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

    public class Holder {
        TextView foodname, quantity, calorie;    
    }    
    public View getView(final int position, View view, ViewGroup parent) {
        Holder holder = new Holder();
        view = inflater.inflate(R.layout.program_list, null);
        // Locate the TextViews in listview_item.xml
        holder.foodname = (TextView) view.findViewById(R.id.textView1);
         // Set the results into TextViews            holder.foodname.setText(allFoodItemlist.get(position).getName().toString());    
        return view;
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        allFoodItemlist.clear();
        if (charText.length() == 0) {
            allFoodItemlist.addAll(arraylist);
        } else {
            for (AllFoodItem wp : arraylist) {
                if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
                    allFoodItemlist.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }

}

MainActivity.Java

filter()メソッドを使用して、EditTextでListViewAdapterクラス適用フィルターを使用します

inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                // When user changed the Text
                foodname = (inputSearch.getText().toString()).trim();

                // filter the data of edit Text using filter method in ListViewAdapter
                String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
                adapter.filter(text);
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {

                userGet();
                // TODO Auto-generated method stub
            }
        });
2
Jatin Raghav