带有CheckBox的ListView,实现删除和选中功能

本文介绍如何在Android中实现一个ListView,其中包含CheckBox,用于实现选择和删除功能。通过自定义Adapter,结合getView方法设置CheckBox的状态,并在点击事件中更新数据。布局文件包括image、textview和checkbox,注意对checkbox的focusable属性进行设置。在Activity中,监听ListView的点击事件,根据CheckBox的状态更新数据,并提供删除功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android实现带有CheckBox的ListView


[html]  view plain copy
  1. package com.zwq.umeng;      
  2.       
  3. import java.util.ArrayList;      
  4. import java.util.HashMap;      
  5. import java.util.List;      
  6. import java.util.Map;      
  7.       
  8. import android.content.Context;      
  9. import android.view.LayoutInflater;      
  10. import android.view.View;      
  11. import android.view.ViewGroup;      
  12. import android.widget.BaseAdapter;      
  13. import android.widget.CheckBox;      
  14. import android.widget.ImageView;      
  15. import android.widget.TextView;      
  16.       
  17. public class MyAdapter extends BaseAdapter {      
  18.     private LayoutInflater mInflater;      
  19.     private List<Map<String, Object>> mData;      
  20.     public static Map<Integer, Boolean> isSelected;      
  21.       
  22.     public MyAdapter(Context context) {      
  23.         mInflater = LayoutInflater.from(context);      
  24.         init();      
  25.     }      
  26.       
  27.     //初始化      
  28.     private void init() {      
  29.         mData=new ArrayList<Map<String, Object>>();      
  30.         for (int i = 0; i < 5; i++) {      
  31.             Map<String, Object> map = new HashMap<String, Object>();      
  32.             map.put("img", R.drawable.icon);      
  33.             map.put("title", "第" + (i + 1) + "行的标题");      
  34.             mData.add(map);      
  35.         }      
  36.         //这儿定义isSelected这个map是记录每个listitem的状态,初始状态全部为false。      
  37.         isSelected = new HashMap<Integer, Boolean>();      
  38.         for (int i = 0; i < mData.size(); i++) {      
  39.             isSelected.put(i, false);      
  40.         }      
  41.     }      
  42.       
  43.     @Override      
  44.     public int getCount() {      
  45.         return mData.size();      
  46.     }      
  47.       
  48.     @Override      
  49.     public Object getItem(int position) {      
  50.         return null;      
  51.     }      
  52.       
  53.     @Override      
  54.     public long getItemId(int position) {      
  55.         return 0;      
  56.     }      
  57.       
  58.     @Override      
  59.     public View getView(int position, View convertView, ViewGroup parent) {      
  60.         ViewHolder holder = null;      
  61.         //convertView为null的时候初始化convertView。      
  62.         if (convertView == null) {      
  63.             holder = new ViewHolder();      
  64.             convertView = mInflater.inflate(R.layout.vlist, null);      
  65.             holder.img = (ImageView) convertView.findViewById(R.id.img);      
  66.             holder.title = (TextView) convertView.findViewById(R.id.title);      
  67.             holder.cBox = (CheckBox) convertView.findViewById(R.id.cb);      
  68.             convertView.setTag(holder);      
  69.         } else {      
  70.             holder = (ViewHolder) convertView.getTag();      
  71.         }      
  72.         holder.img.setBackgroundResource((Integer) mData.get(position).get(      
  73.                 "img"));      
  74.         holder.title.setText(mData.get(position).get("title").toString());      
  75.         holder.cBox.setChecked(isSelected.get(position));      
  76.         return convertView;      
  77.     }      
  78.       
  79.     public final class ViewHolder {      
  80.         public ImageView img;      
  81.         public TextView title;      
  82.         public CheckBox cBox;      
  83.     }      
  84. }      


项目要用到一个listview,要求是可以显示图片,后面还有有复选框。

先新建一个MyAdapter类,继承自BaseAdapter。在MyAdapter中实现对数据的绑定,我这儿由于是测试的,所以把数据写死了。

Java代码 

上面类中要注意getView()方法中对数据的处理。

 

接下要新建一个list.xml文件,这个就是布局image、textview、checkbox。

[html]  view plain copy
  1.     <TextView       
  2.         android:id="@+id/title"      
  3.         android:textSize="18dip"      
  4.         android:layout_weight="1"      
  5.         android:layout_width="wrap_content"      
  6.         android:layout_height="wrap_content"/>      
  7.     <CheckBox      
  8.         android:id="@+id/cb"      
  9.         android:layout_width="wrap_content"      
  10.         android:layout_height="wrap_content"      
  11.         android:focusable="false"      
  12.         android:focusableInTouchMode="false"      
  13.         android:clickable="false"             
  14.         android:checkMark="?android:attr/listChoiceIndicatorMultiple"/>      
  15. </LinearLayout>  

android:layout_weight="1"这一句可以使中间的textview权重增大,从而后面的checkbok可以居右显示。

[html]  view plain copy
  1. android:focusable="false"     
  2.         android:focusableInTouchMode="false"     
  3.         android:clickable="false"    

这三句很重要,如果不加就会出现错误。

由于checkbox的点击事件优先级比listview的高,所以要在checkbox中添加android:focusable="false",使得checkbox初始的时候没有获取焦点。

接下来在main.xml中添加Listview组件

Java代码

[html]  view plain copy
  1. <ListView      
  2.         android:id="@+id/lv"      
  3.         android:layout_width="fill_parent"       
  4.         android:layout_height="wrap_content"/>   

接下来就是在activity中调用:

Java代码 

[html]  view plain copy
  1. list=(ListView)findViewById(R.id.lv);      
  2.         MyAdapter adapter=new MyAdapter(this);      
  3.         list.setAdapter(adapter);      
  4.         list.setItemsCanFocus(false);      
  5.         list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);      
  6.       
  7.         list.setOnItemClickListener(new OnItemClickListener(){      
  8.             @Override      
  9.             public void onItemClick(AdapterView<?> parent, View view,      
  10.                     int position, long id) {      
  11.                 ViewHolder vHollder = (ViewHolder) view.getTag();      
  12. //在每次获取点击的item时将对于的checkbox状态改变,同时修改map的值。      
  13.                 vHollder.cBox.toggle();      
  14.                 MyAdapter.isSelected.put(position, vHollder.cBox.isChecked());      
  15.             }      
  16.         });   

最新看一下效果图:

效果图

要获取哪些项目被选择了,可以这样测试:

Java代码

[html]  view plain copy
  1. OnClickListener bPop = new OnClickListener() {      
  2.         @Override      
  3.         public void onClick(View v) {      
  4.             for(int i=0;i<list.getCount();i++){      
  5.                 if(MyAdapter.isSelected.get(i)){      
  6.                     ViewHolder vHollder = (ViewHolder) list.getChildAt(i).getTag();      
  7. Log.i(TAG, "--onClick --"+vHollder.title.getText());      
  8.                 }      
  9.             }      
  10.         }      
  11.     };     

总结

1、数据可以在Activity中获取,在初始化Adapter的时候当做参数传递过去,这样就可以是list编程动态的。

2、对MyAdapter中getview的理解不够,尤其是convertView.setTag(holder),



ListView结合Checkbox实现删除功能


效果图


实现要点:

1 Listview是一个动态的组件,实现监听Listview里的动作需要用到BaseAdapter类

2 数据存储结构ArrayList<HashMap<String, String>> list, 第一个string存放flag,用以判断是否选中;第二个string存放msg

3 一旦数据有变,必须使用mAdapter.notifyDataSetChanged(); 否则view无法得知数据变化,从而会报错


一共由以下文件组成(仅核心部分,参考慎用)

JAVA

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.   Button btnDelete;  
  2.   ListView lv;  
  3. Context mContext;  
  4. MyListAdapter adapter;   
  5. private ArrayList<HashMap<String, String>> list;  
  6.   
  7.   @Override  
  8.   public void onCreate(Bundle savedInstanceState) {  
  9.       super.onCreate(savedInstanceState);   
  10.         
  11.       requestWindowFeature(Window.FEATURE_NO_TITLE);   
  12.       setContentView(R.layout.activity_carton_no_main);  
  13.       SysApplication.getInstance().addActivity(this);   
  14.         
  15.       btnDelete = (Button)findViewById(R.id.ctn_no_scan_delete_btn);   
  16.       lv = (ListView)findViewById(R.id.carton_no_list);  
  17.         
  18.         list = new ArrayList<HashMap<String, String>>();    
  19.         mAdapter = new MyListAdapter(list, this);  
  20.         lv.setAdapter(mAdapter);  
  21.           
  22.         //insert something  
  23.         HashMap<String, String> map = new HashMap<String, String>();  
  24.             map.put("content"'test');  
  25.             map.put("flag""false");  
  26.             list.add(map);   
  27.               
  28.             btnDelete.setOnClickListener(new View.OnClickListener() {   
  29.             @Override  
  30.             public void onClick(View v) {   
  31.                 Iterator<HashMap<String, String>> iterator = list.iterator();  
  32.                 while (iterator.hasNext()) {  
  33.                     HashMap<String, String> temp = iterator.next();  
  34.                     if (temp.get("flag").equals("true")) {  
  35.                         iterator.remove();  
  36.                     }  
  37.                 }  
  38.                 checkNum = 0;  
  39.                 //if you have changed list, please excute mAdapter.notifyDataSetChanged();   
  40.                 dataChanged();  
  41.             }  
  42.         });  
  43.               
  44.             lv.setOnItemClickListener(new OnItemClickListener() {  
  45.             @Override  
  46.             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
  47.                     long arg3) {    
  48.                 ViewHolder holder = (ViewHolder) arg1.getTag();    
  49.                 holder.cb.toggle();  
  50.                   
  51.                 //store checkbox's status   
  52.                 if (holder.cb.isChecked() == true) {  
  53.                     list.get(arg2).put("flag""true");  
  54.                     checkNum++;  
  55.                 } else {  
  56.                     list.get(arg2).put("flag""false");  
  57.                     checkNum--;  
  58.                 }   
  59.             }  
  60.         });  
  61.   }  
  62. public class MyListAdapter extends BaseAdapter{  
  63.   
  64.         private ArrayList<HashMap<String, String>> list;  
  65.            
  66.         private Context context;  
  67.            
  68.         private LayoutInflater inflater = null;  
  69.            
  70.         public MyListAdapter(ArrayList<HashMap<String, String>> list, Context context){  
  71.             this.context = context;  
  72.             this.list = list;  
  73.             inflater = LayoutInflater.from(context);  
  74.         }  
  75.           
  76.         @Override  
  77.         public int getCount() {  
  78.                
  79.             return list.size();  
  80.         }  
  81.         @Override  
  82.         public Object getItem(int position) {  
  83.            
  84.             return list.get(position);  
  85.         }  
  86.         @Override  
  87.         public long getItemId(int position) {  
  88.            
  89.             return position;  
  90.         }  
  91.         @Override  
  92.         public View getView(int position, View convertView, ViewGroup parent){  
  93.             ViewHolder holder = null;  
  94.             if (convertView == null) {  
  95.                 holder = new ViewHolder();  
  96.                 convertView = inflater.inflate(R.layout.activity_carton_no_list, null);  
  97.                 holder.tv = (TextView) convertView.findViewById(R.id.carton_no_list_name);  
  98.                 holder.cb = (CheckBox) convertView.findViewById(R.id.carton_no_list_checked);   
  99.                 convertView.setTag(holder);  
  100.             } else {   
  101.                 holder = (ViewHolder) convertView.getTag();  
  102.             }  
  103.             //init view  
  104.             holder.tv.setText(list.get(position).get("content").toString());   
  105.             holder.cb.setChecked(list.get(position).get("flag").equals("true"));  
  106.             return convertView;  
  107.         }  
  108.           
  109.         final class ViewHolder{  
  110.             TextView tv;  
  111.             CheckBox cb;   
  112.         }  
  113.     }  
  114. private void dataChanged(){  
  115.   
  116.  mAdapter.notifyDataSetChanged();   
  117.  }  


XML 

1/2

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:tools="http://schemas.android.com/tools"  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:background="@color/white"  
  7.     android:orientation="vertical" >  
  8.       
  9.   <LinearLayout  
  10.      android:layout_width="wrap_content"  
  11.      android:layout_height="wrap_content"  
  12.      android:orientation="horizontal"  
  13.      android:descendantFocusability="blocksDescendants">   
  14.         
  15.       <CheckBox  
  16.         android:id="@+id/carton_no_list_checked"  
  17.         android:layout_width="wrap_content"  
  18.         android:layout_height="wrap_content"  
  19.         android:clickable="false"  
  20.         android:focusable="false"  
  21.         android:focusableInTouchMode="false"  
  22.         android:gravity="center_vertical" />  
  23.   
  24.       <TextView  
  25.           android:id="@+id/carton_no_list_name"  
  26.           android:layout_width="fill_parent"  
  27.           android:layout_height="wrap_content"  
  28.           android:layout_gravity="center"  
  29.           android:layout_marginLeft="10dp"  
  30.           android:layout_weight="1"  
  31.           android:text="Name"  
  32.           android:textColor="@color/viewfinder_mask"  
  33.           android:textSize="20dp" />  
  34.          
  35.   </LinearLayout>  
  36. </LinearLayout>  

2/2

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:tools="http://schemas.android.com/tools"  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:background="@color/white"  
  7.     android:orientation="vertical" >  
  8.    
  9.     <LinearLayout    
  10.         android:orientation="vertical"  
  11.         android:layout_width="match_parent"  
  12.         android:layout_height="match_parent"   
  13.         android:layout_weight="0.1">   
  14.         <ListView  
  15.            android:id="@+id/carton_no_list"  
  16.            android:layout_width="match_parent"  
  17.            android:layout_height="fill_parent"/>  
  18.     </LinearLayout>  
  19.         <LinearLayout  
  20.         android:id="@+id/LinearLayout1"  
  21.         android:layout_width="match_parent"  
  22.         android:layout_height="match_parent"     
  23.         android:layout_weight="0.7"  
  24.         android:orientation="horizontal" >  
  25.   
  26.         <Button  
  27.             android:id="@+id/ctn_no_scan_delete_btn"  
  28.             android:layout_width="match_parent"  
  29.             android:layout_height="50dp"  
  30.             android:layout_weight="0.1"   
  31.             android:text="Delete" />   
  32.            
  33.     </LinearLayout>    
  34. </LinearLayout>  


同理,实现radiobox,也是一样的道理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值