0

我有ListView自定义Checkable列表项布局。我ListViewCHOICE_MODE_MULTIPLE模式下工作,我想检查CheckBoxcheked 父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类:

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();
    }

}
4

1 回答 1

1

由于您在 XML 中定义子项,因此我将遍历 CheckedRelativeLayout 中的所有子项,如果它们实现了 Checkable,则对它们调用 setChecked 并传入 CheckedRelativeLayout 的选中状态。

如果您要在代码中构建布局(这意味着您保证孩子总是在那里),您可以在 CheckedRelativeLayout 的状态更改时切换复选框。

于 2012-10-04T18:26:00.227 回答