android中ListView的setItemChecked方法 实现多选

在Android中实现ListView的多选功能,需要设置XML中的choiceMode属性为singleChoice或multipleChoice,并确保listView的item是checkable的。对于自定义布局的item,需要继承Checkable接口,例如创建一个CheckableLinearLayout类,覆盖setChecked、isChecked和toggle方法,并在切换状态时改变颜色。

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

1.要在XML中为listView设置choiceMode  为singleChoice或者mutipleChoice


也可以在代码中设置 listView.setChoiceMode(int mode);

2.listView的item一定要是checkable的。否则不会生效。这一点也是从网上看的资料,具体没有研究了。

最常见还是集成baseAdapter 使用的自定义布局这种情况,请看第三点。

3.对于自定义的xml布局,item的布局需要实现Checkable接口。例如常见的item根布局为LinearLayout,则我们需要自定义一个LinearLayout

[java]  view plain  copy
  1. public class CheckableLinearLayout extends LinearLayout implements Checkable {  
  2.     private boolean isChecked = false;  
  3.   
  4.     public CheckableLinearLayout(Context context, AttributeSet attrs, int defStyle) {  
  5.         super(context, attrs, defStyle);  
  6.     }  
  7.   
  8.     public CheckableLinearLayout(Context context, AttributeSet attrs) {  
  9.         super(context, attrs);  
  10.     }  
  11.   
  12.     public CheckableLinearLayout(Context context) {  
  13.         super(context);  
  14.     }  
  15.   
  16.     @Override  
  17.     public void setChecked(boolean checked) {  
  18.         isChecked = checked;  
  19.         changeColor(checked);  
  20.     }  
  21.   
  22.     @Override  
  23.     public boolean isChecked() {  
  24.   
  25.         return isChecked;  
  26.     }  
  27.   
  28.     @Override  
  29.     public void toggle() {  
  30.         this.isChecked = !this.isChecked;  
  31.         changeColor(this.isChecked);  
  32.   
  33.     }  
  34.   
  35.     private void changeColor(boolean isChecked) {  
  36.         //根据check的状态切换颜色  
  37.         if (isChecked) {  
  38.             setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));  
  39.         } else {  
  40.             setBackgroundColor(getResources().getColor(android.R.color.transparent));  
  41.         }  
  42.     }  
  43.   
  44. }  
然后在xml中使用该布局替代原生的LinearLayout
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值