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) {
-
- if (isChecked) {
- setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
- } else {
- setBackgroundColor(getResources().getColor(android.R.color.transparent));
- }
- }
-
- }
然后在xml中使用该布局替代原生的LinearLayout