Make RelativeLayout checkable

后端 未结 4 1151
长发绾君心
长发绾君心 2021-01-03 04:53

I try to write my own CheckBox using RelativeLayout with TextView and FrameLayout (with selector on background) inside.

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-03 05:45

    There seem to be two UI patterns for multi-select lists in Holo (in the context of ActionMode): using checkboxes or highlighting.

    If all you need is highlighting, you can use this simpler method:

    Make your list item layout use for the root a class like this one:

    public class CheckableRelativeLayout extends RelativeLayout implements Checkable {
    private static final int[] STATE_CHECKABLE = {R.attr.state_pressed};
    boolean checked = false;
    
    public void setChecked(boolean checked) {
        this.checked = checked;
        refreshDrawableState();
    }
    
    public boolean isChecked() {
        return checked;
    }
    
    public void toggle() {
        setChecked(!checked);
    }
    
    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
        int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (checked) mergeDrawableStates(drawableState, STATE_CHECKABLE);
    
        return drawableState;
    }
    }
    

    and make sure the root element in your list item layout uses

    android:background="?android:attr/listChoiceBackgroundIndicator"
    

    I know this is not really an answer to your question (you wanted an actual checkbox), but I haven't seen this documented anywhere.

    The ListView uses the Checkable interface to determine whether it can rely on the list item element to display the checkable state or if it should try to display it itself.

提交回复
热议问题