我有ListView
个自定义Checkable
列表项布局。我的ListView
工作在CHOICE_MODE_MULTIPLE
模式,我想检查已解除父项CheckBox
项的子com.domain.CheckedRelativeLayout
视图。我该怎么办?
<?xml version="1.0" encoding="utf-8"?>
<com.domain.CheckedRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants"
android:background="@drawable/selector">
<RelativeLayout
android:id="@+id/rl_data"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:paddingTop="2dp"
android:paddingBottom="2dp">
...
</RelativeLayout>
<CheckBox android:id="@+id/cb_select"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="6dp"
android:text="" />
</com.domain.CheckedRelativeLayout>
java class:
public class CheckedRelativeLayout extends RelativeLayout implements Checkable {
private boolean mChecked;
private static final int[] CheckedStateSet = {
android.R.attr.state_checked
};
public CheckedRelativeLayout(Context context) {
super(context);
}
public CheckedRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean isChecked() {
Log.v(getClass().getName(), " IS CHECKED ");
return mChecked;
}
public void setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
refreshDrawableState();
}
}
@Override
public void toggle() {
mChecked = !mChecked;
Log.v(getClass().getName(), " TOGGLE ");
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CheckedStateSet);
}
return drawableState;
}
@Override
public boolean performClick() {
toggle();
return super.performClick();
}
}
答案 0 :(得分:1)
由于您在XML中定义子项,我只是遍历CheckedRelativeLayout中的所有子项,如果它们实现了Checkable,则调用setChecked并传入CheckedRelativeLayout的checked状态。
如果你要在代码中构建布局(意味着你保证孩子们总是在那里),你可以在CheckedRelativeLayout的状态发生变化时切换复选框。