程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> android-使用 arrayadapter 來 filter 一個 listview

android-使用 arrayadapter 來 filter 一個 listview

編輯:編程綜合問答
使用 arrayadapter 來 filter 一個 listview

我使用 arrayadapter 來 filter 一個 listview。Arraydapter 的參數是一個String[][]。但是沒有成功,必須要重寫 Filter interface嗎?要是這樣的話,如何重寫呢?
filter 數組的每一個位置:

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();                 
}        
});

The adapter code:

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;
}

最佳回答:


把字符串數組放在 ArrayList 中,然後把它傳遞到 Adapter。使用下面的代碼或者用 String[]更改下面的代碼。
需要在 Adapter 類中實現 Filterable ,重寫 getFilter()。
參考下面的代碼關於 Filtering custom 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;
            }
        }
    }
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved