public interface Checkable
凡是继承了此接口的类 例如: CheckBox, CheckedTextView, CompoundButton, RadioButton, ToggleButton 都是实现了这个接口 ,所以他们都有一个 checked 方法
再比如自定义的view继承了 Checkable 后也会有一个 checked的方法
例如 我们要实现一个在listitem中有个checkbox的东东 我们便可以自定义listview 的item 让他如实现checkable 然后他就会有checked,这里呢 我们要注意:在listview中我们要设置 android:choiceMode="multipleChoice"
而后 在我们点击 item 的时候 便会把事件传到 item中 checkbox中
代码:
item
<com.example.listview_chack.Items
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:clickable="false"
android:focusable="false" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="17dp"
android:layout_marginTop="17dp"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp" />
<TextView
android:id="@+id/subtitle"
android:textSize="12sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</com.example.listview_chack.Items>
自定义 item
package com.example.listview_chack;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Checkable;
import android.widget.FrameLayout;
public class Items extends FrameLayout implements Checkable{
private boolean mChecked = false;
public Items(Context context,AttributeSet attrs) {
super(context,attrs);
// TODO 自动生成的构造函数存根
}
@Override
public boolean isChecked() {
// TODO 自动生成的方法存根
return mChecked;
}
@Override
public void setChecked(boolean checked) {
// TODO 自动生成的方法存根
if (mChecked != checked) {
mChecked = checked;
refreshDrawableState();
for (int i = 0, len = getChildCount(); i < len; i++) {
View child = getChildAt(i);
if(child instanceof Checkable){
((Checkable) child).setChecked(checked);
}
}
}
}
@Override
public void toggle() {
// TODO 自动生成的方法存根
setChecked(!mChecked);
}
}
下面我们来说 一下 其中的方法
public abstract boolean isChecked ()
查询当前视图控件的选中状态。
返回:
返回一个boolean的值来表示当前视图控件的选中状态,如果当前控件被选中,返回true值,否则返回false值。
(译者注:并不一定是控件上显示了对号或者点就是被选中,很可能某个思维不同于常人的程序员会把有对号的定义为未选中而返回一个false。当然这只是可能,按照常理来说还是有对号和点的表示选中true,反之亦然。)
public abstract void setChecked (boolean checked)
设置当前视图控件的选中状态。(译者注:
执行前 | 执行 | 执行后 |
任何状态 | setChecked(true) | 选中 |
任何状态 | setChecked(false) | 未选中 |
参数:
checked 指定控件的选中状态true表示设置为选中,false为未选中。
public abstract void toggle ()
此方法用来切换当前视图控件的选中状态。(译者注:即将视图控件的当前状态变为其相反状态
执行前 | 执行 | 执行后 |
选中 | toggle() | 未选中 |
未选中 | toggle() | 选中 |
一句代码 来讲 初始 状态都设置false 然后 当我们点击item的时候 执行 toggle() 改变状态
其次 设置listview全选
代码
all_sel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(int i=0;i<dataList.size();i++){
listView.setItemChecked(i, true);
}
}
});
以上为自己理解 如有误解 请指正 我会很感激。