android中ListView的setItemChecked方法

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


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

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

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

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

public class CheckableLinearLayout extends LinearLayout implements Checkable {
	private boolean isChecked = false;

	public CheckableLinearLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public CheckableLinearLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CheckableLinearLayout(Context context) {
		super(context);
	}

	@Override
	public void setChecked(boolean checked) {
		isChecked = checked;
		changeColor(checked);
	}

	@Override
	public boolean isChecked() {

		return isChecked;
	}

	@Override
	public void toggle() {
		this.isChecked = !this.isChecked;
		changeColor(this.isChecked);

	}

	private void changeColor(boolean isChecked) {
		//根据check的状态切换颜色
		if (isChecked) {
			setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
		} else {
			setBackgroundColor(getResources().getColor(android.R.color.transparent));
		}
	}

}
然后在xml中使用该布局替代原生的LinearLayout



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值