ListView中加入LinearLayout listview baseadapter 的filter

ListView中加入LinearLayout【二】

分类: android 布局 ListView   98人阅读  评论(0)  收藏  举报

这个主要是补充《ListView中加入LinearLayout【一】》中的一些限制


在【一】 中,我试了很多方法添加网络上的图片,在无数次失败后,终于成功添加。

{此方法不建议使用  要用listView建议重写BaseAdapter的getView方法  自己想怎么定义Adapter就怎么定义  就不用费这么大的周折了-----2011.11.23

}

这个就要用到Android的API源码,我改写了下SimpleAdapter这个类(主要是重写一个setViewImage方法)。并命名为MyAdapter.java
另外添加了一个把URL资源转换成BitMap图像的类

代码如下:

[java]  view plain copy print ?
  1.  /** 
  2.   * Class Name: UrlToBitmap  
  3.   * @author Pweibo 
  4.   *  Turn an Url image to Bitmap type 
  5.   */  
  6. public class UrlToBitmap {  
  7.     private Bitmap bitmap;  
  8.       
  9.     /** 
  10.      *  
  11.      * @param myFileUrl An image of URL type  
  12.      */  
  13.     public UrlToBitmap(URL myFileUrl) {     
  14. //         URL myFileUrl = null;     
  15.             bitmap = null;       
  16.              
  17.            try {     
  18.             HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();     
  19.             conn.setDoInput(true);     
  20.             conn.connect();     
  21.             InputStream is = conn.getInputStream();     
  22.             bitmap = BitmapFactory.decodeStream(is);     
  23.             is.close();     
  24.            } catch (IOException e) {     
  25.             e.printStackTrace();     
  26.            }      
  27.         }   
  28.     /** 
  29.      *  
  30.      * @return A Bitmap type 
  31.      */  
  32.     public Bitmap reutrnBitmap(){  
  33.         return bitmap;  
  34.     }  
  35. }  

[java]  view plain copy print ?
  1. /** 
  2.  *  Class Name: MyAdapter 
  3.  * @author Pcd  
  4.  * </br>rewriting code from SimpleAdapter  
  5.  * 
  6.  */  
  7. public class MyAdapter extends BaseAdapter implements Filterable {  
  8.         private int[] mTo;  
  9.         private String[] mFrom;  
  10.         private ViewBinder mViewBinder;  
  11.   
  12.         private List<? extends Map<String, ?>> mData;  
  13.   
  14.         private int mResource;  
  15.         private int mDropDownResource;  
  16.         private LayoutInflater mInflater;  
  17.   
  18.         private SimpleFilter mFilter;  
  19.         private ArrayList<Map<String, ?>> mUnfilteredData;  
  20.   
  21.         /** 
  22.          * Constructor 
  23.          *  
  24.          * @param context The context where the View associated with this SimpleAdapter is running 
  25.          * @param data A List of Maps. Each entry in the List corresponds to one row in the list. The 
  26.          *        Maps contain the data for each row, and should include all the entries specified in 
  27.          *        "from" 
  28.          * @param resource Resource identifier of a view layout that defines the views for this list 
  29.          *        item. The layout file should include at least those named views defined in "to" 
  30.          * @param from A list of column names that will be added to the Map associated with each 
  31.          *        item. 
  32.          * @param to The views that should display column in the "from" parameter. These should all be 
  33.          *        TextViews. The first N views in this list are given the values of the first N columns 
  34.          *        in the from parameter. 
  35.          */  
  36.         public MyAdapter(Context context, List<? extends Map<String, ?>> data,  
  37.                 int resource, String[] from, int[] to) {  
  38.             mData = data;  
  39.             mResource = mDropDownResource = resource;  
  40.             mFrom = from;  
  41.             mTo = to;  
  42.             mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  43.         }  
  44.   
  45.           
  46.         /** 
  47.          * @see android.widget.Adapter#getCount() 
  48.          */  
  49.         public int getCount() {  
  50.             return mData.size();  
  51.         }  
  52.   
  53.         /** 
  54.          * @see android.widget.Adapter#getItem(int) 
  55.          */  
  56.         public Object getItem(int position) {  
  57.             return mData.get(position);  
  58.         }  
  59.   
  60.         /** 
  61.          * @see android.widget.Adapter#getItemId(int) 
  62.          */  
  63.         public long getItemId(int position) {  
  64.             return position;  
  65.         }  
  66.   
  67.         /** 
  68.          * @see android.widget.Adapter#getView(int, View, ViewGroup) 
  69.          */  
  70.         public View getView(int position, View convertView, ViewGroup parent) {  
  71.             return createViewFromResource(position, convertView, parent, mResource);  
  72.         }  
  73.   
  74.         private View createViewFromResource(int position, View convertView,  
  75.                 ViewGroup parent, int resource) {  
  76.             View v;  
  77.             if (convertView == null) {  
  78.                 v = mInflater.inflate(resource, parent, false);  
  79.             } else {  
  80.                 v = convertView;  
  81.             }  
  82.   
  83.             bindView(position, v);  
  84.   
  85.             return v;  
  86.         }  
  87.   
  88.         /** 
  89.          * <p>Sets the layout resource to create the drop down views.</p> 
  90.          * 
  91.          * @param resource the layout resource defining the drop down views 
  92.          * @see #getDropDownView(int, android.view.View, android.view.ViewGroup) 
  93.          */  
  94.         public void setDropDownViewResource(int resource) {  
  95.             this.mDropDownResource = resource;  
  96.         }  
  97.   
  98.         @Override  
  99.         public View getDropDownView(int position, View convertView, ViewGroup parent) {  
  100.             return createViewFromResource(position, convertView, parent, mDropDownResource);  
  101.         }  
  102.   
  103.         private void bindView(int position, View view) {  
  104.             final Map dataSet = mData.get(position);  
  105.             if (dataSet == null) {  
  106.                 return;  
  107.             }  
  108.   
  109.             final ViewBinder binder = mViewBinder;  
  110.             final String[] from = mFrom;  
  111.             final int[] to = mTo;  
  112.             final int count = to.length;  
  113.   
  114.             for (int i = 0; i < count; i++) {  
  115.                 final View v = view.findViewById(to[i]);  
  116.                 if (v != null) {  
  117.                     final Object data = dataSet.get(from[i]);  
  118.                     String text = data == null ? "" : data.toString();  
  119.                     if (text == null) {  
  120.                         text = "";  
  121.                     }  
  122.   
  123.                     boolean bound = false;  
  124.                     if (binder != null) {  
  125.                         bound = binder.setViewValue(v, data, text);  
  126.                     }  
  127.   
  128.                     if (!bound) {  
  129.                         if (v instanceof Checkable) {  
  130.                             if (data instanceof Boolean) {  
  131.                                 ((Checkable) v).setChecked((Boolean) data);  
  132.                             } else if (v instanceof TextView) {  
  133.                                 // Note: keep the instanceof TextView check at the bottom of these  
  134.                                 // ifs since a lot of views are TextViews (e.g. CheckBoxes).  
  135.                                 setViewText((TextView) v, text);  
  136.                             } else {  
  137.                                 throw new IllegalStateException(v.getClass().getName() +  
  138.                                         " should be bound to a Boolean, not a " +  
  139.                                         (data == null ? "<unknown type>" : data.getClass()));  
  140.                             }  
  141.                         } else if (v instanceof TextView) {  
  142.                             // Note: keep the instanceof TextView check at the bottom of these  
  143.                             // ifs since a lot of views are TextViews (e.g. CheckBoxes).  
  144.                             setViewText((TextView) v, text);  
  145.                         } else if (v instanceof ImageView) {  
  146.                             if (data instanceof Integer) {  
  147.                                 setViewImage((ImageView) v, (Integer) data);                              
  148.                             } else if(data instanceof Bitmap){  
  149.                                 setViewImage((ImageView) v, (Bitmap) data);  
  150.                             }                    
  151.                             else {  
  152.                                 setViewImage((ImageView) v, text);  
  153.                             }  
  154.                         } else {  
  155.                             throw new IllegalStateException(v.getClass().getName() + " is not a " +  
  156.                                     " view that can be bounds by this SimpleAdapter");  
  157.                         }  
  158.                     }  
  159.                 }  
  160.             }  
  161.         }  
  162.   
  163.         /** 
  164.          * Returns the {@link ViewBinder} used to bind data to views. 
  165.          * 
  166.          * @return a ViewBinder or null if the binder does not exist 
  167.          * 
  168.          * @see #setViewBinder(android.widget.SimpleAdapter.ViewBinder) 
  169.          */  
  170.         public ViewBinder getViewBinder() {  
  171.             return mViewBinder;  
  172.         }  
  173.   
  174.         /** 
  175.          * Sets the binder used to bind data to views. 
  176.          * 
  177.          * @param viewBinder the binder used to bind data to views, can be null to 
  178.          *        remove the existing binder 
  179.          * 
  180.          * @see #getViewBinder() 
  181.          */  
  182.         public void setViewBinder(ViewBinder viewBinder) {  
  183.             mViewBinder = viewBinder;  
  184.         }  
  185.   
  186.         public void setViewImage(ImageView v, Bitmap bm) {  
  187.             try {  
  188.                 v.setImageBitmap(bm);  
  189.             } catch (Exception e ) {  
  190.                 System.err.print("Erro in ViewImage");  
  191.              }  
  192.         }   
  193.         /** 
  194.          * Called by bindView() to set the image for an ImageView but only if 
  195.          * there is no existing ViewBinder or if the existing ViewBinder cannot 
  196.          * handle binding to an ImageView. 
  197.          * 
  198.          * This method is called instead of {@link #setViewImage(ImageView, String)} 
  199.          * if the supplied data is an int or Integer. 
  200.          * 
  201.          * @param v ImageView to receive an image 
  202.          * @param value the value retrieved from the data set 
  203.          * 
  204.          * @see #setViewImage(ImageView, String) 
  205.          */  
  206.         public void setViewImage(ImageView v, int value) {  
  207.             v.setImageResource(value);  
  208.         }  
  209.   
  210.         /** 
  211.          * Called by bindView() to set the image for an ImageView but only if 
  212.          * there is no existing ViewBinder or if the existing ViewBinder cannot 
  213.          * handle binding to an ImageView. 
  214.          * 
  215.          * By default, the value will be treated as an image resource. If the 
  216.          * value cannot be used as an image resource, the value is used as an 
  217.          * image Uri. 
  218.          * 
  219.          * This method is called instead of {@link #setViewImage(ImageView, int)} 
  220.          * if the supplied data is not an int or Integer. 
  221.          * 
  222.          * @param v ImageView to receive an image 
  223.          * @param value the value retrieved from the data set 
  224.          * 
  225.          * @see #setViewImage(ImageView, int)  
  226.          */  
  227.         public void setViewImage(ImageView v, String value) {  
  228.             try {  
  229.                 v.setImageResource(Integer.parseInt(value));  
  230.             } catch (NumberFormatException nfe) {  
  231.                 v.setImageURI(Uri.parse(value));  
  232.             }  
  233.         }  
  234.   
  235.         /** 
  236.          * Called by bindView() to set the text for a TextView but only if 
  237.          * there is no existing ViewBinder or if the existing ViewBinder cannot 
  238.          * handle binding to an TextView. 
  239.          * 
  240.          * @param v TextView to receive text 
  241.          * @param text the text to be set for the TextView 
  242.          */  
  243.         public void setViewText(TextView v, String text) {  
  244.             v.setText(text);  
  245.         }  
  246.   
  247.         public Filter getFilter() {  
  248.             if (mFilter == null) {  
  249.                 mFilter = new SimpleFilter();  
  250.             }  
  251.             return mFilter;  
  252.         }  
  253.   
  254.         /** 
  255.          * This class can be used by external clients of SimpleAdapter to bind 
  256.          * values to views. 
  257.          * 
  258.          * You should use this class to bind values to views that are not 
  259.          * directly supported by SimpleAdapter or to change the way binding 
  260.          * occurs for views supported by SimpleAdapter. 
  261.          * 
  262.          * @see SimpleAdapter#setViewImage(ImageView, int) 
  263.          * @see SimpleAdapter#setViewImage(ImageView, String) 
  264.          * @see SimpleAdapter#setViewText(TextView, String) 
  265.          */  
  266.         public static interface ViewBinder {  
  267.             /** 
  268.              * Binds the specified data to the specified view. 
  269.              * 
  270.              * When binding is handled by this ViewBinder, this method must return true. 
  271.              * If this method returns false, SimpleAdapter will attempts to handle 
  272.              * the binding on its own. 
  273.              * 
  274.              * @param view the view to bind the data to 
  275.              * @param data the data to bind to the view 
  276.              * @param textRepresentation a safe String representation of the supplied data: 
  277.              *        it is either the result of data.toString() or an empty String but it 
  278.              *        is never null 
  279.              * 
  280.              * @return true if the data was bound to the view, false otherwise 
  281.              */  
  282.             boolean setViewValue(View view, Object data, String textRepresentation);  
  283.         }  
  284.   
  285.         /** 
  286.          * <p>An array filters constrains the content of the array adapter with 
  287.          * a prefix. Each item that does not start with the supplied prefix 
  288.          * is removed from the list.</p> 
  289.          */  
  290.         private class SimpleFilter extends Filter {  
  291.   
  292.             @Override  
  293.             protected FilterResults performFiltering(CharSequence prefix) {  
  294.                 FilterResults results = new FilterResults();  
  295.   
  296.                 if (mUnfilteredData == null) {  
  297.                     mUnfilteredData = new ArrayList<Map<String, ?>>(mData);  
  298.                 }  
  299.   
  300.                 if (prefix == null || prefix.length() == 0) {  
  301.                     ArrayList<Map<String, ?>> list = mUnfilteredData;  
  302.                     results.values = list;  
  303.                     results.count = list.size();  
  304.                 } else {  
  305.                     String prefixString = prefix.toString().toLowerCase();  
  306.   
  307.                     ArrayList<Map<String, ?>> unfilteredValues = mUnfilteredData;  
  308.                     int count = unfilteredValues.size();  
  309.   
  310.                     ArrayList<Map<String, ?>> newValues = new ArrayList<Map<String, ?>>(count);  
  311.   
  312.                     for (int i = 0; i < count; i++) {  
  313.                         Map<String, ?> h = unfilteredValues.get(i);  
  314.                         if (h != null) {  
  315.                               
  316.                             int len = mTo.length;  
  317.   
  318.                             for (int j=0; j<len; j++) {  
  319.                                 String str =  (String)h.get(mFrom[j]);  
  320.                                   
  321.                                 String[] words = str.split(" ");  
  322.                                 int wordCount = words.length;  
  323.                                   
  324.                                 for (int k = 0; k < wordCount; k++) {  
  325.                                     String word = words[k];  
  326.                                       
  327.                                     if (word.toLowerCase().startsWith(prefixString)) {  
  328.                                         newValues.add(h);  
  329.                                         break;  
  330.                                     }  
  331.                                 }  
  332.                             }  
  333.                         }  
  334.                     }  
  335.   
  336.                     results.values = newValues;  
  337.                     results.count = newValues.size();  
  338.                 }  
  339.   
  340.                 return results;  
  341.             }  
  342.   
  343.             @Override  
  344.             protected void publishResults(CharSequence constraint, FilterResults results) {  
  345.                 //noinspection unchecked  
  346.                 mData = (List<Map<String, ?>>) results.values;  
  347.                 if (results.count > 0) {  
  348.                     notifyDataSetChanged();  
  349.                 } else {  
  350.                     notifyDataSetInvalidated();  
  351.                 }  
  352.             }  
  353.         }  
  354.       
  355. }  

其它的XML文件配置和【一】中的一致。

最后,主程序代码如下

/*

[java]  view plain copy print ?
  1.  主Activity代码  
  2. */  
  3. public class ListViewTest extends Activity {    
  4. /** Called when the activity is first created. */    
  5.     private ListView listv;    
  6.     private String urladdress = "http://www.csdnimg.cn/www/images/csdnindex_logo.gif"; //图片的URL地址  
  7.     @Override    
  8.     public void onCreate(Bundle savedInstanceState) {    
  9.     super.onCreate(savedInstanceState);    
  10.     setContentView(R.layout.main);    
  11.     listv = (ListView) findViewById(R.id.list); //关联到mian的ListView    
  12.       
  13.     ArrayList<Map<String, Object>> arrayl = new ArrayList<Map<String, Object>>();    
  14.     Bitmap bm = new UrlToBitmap(urladdress).returnBitMap(); //先把URL资源转成Bitmap  
  15.       
  16.     for(int count = 0; count<15; count++){    
  17.         Map<String, Object> map= new HashMap<String, Object>();    
  18.         map.put(“image”, bm); //放入图片资源    
  19.         map.put(“Text”, “This is a Listview , No. “+ count + ” !”); //放入计数器    
  20.         arrayl.add(map);             
  21.     }     
  22.       
  23.     //注意这里是MyAdapter  
  24.     MyAdapter adapte = new MyAdapter(this,    
  25.     R.layout.content,    
  26.     new String[] {“image”, “Text”},    
  27.     new int[]{R.id.img, R.id.text});  
  28.       
  29.     listv.setAdapter(adapter);    
  30.     }      
  31.  }    

PS : 由于时间紧迫,来不及测试代码,有问题的话可以留言, 谢谢!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值