通过xml

时间:2016-02-23 08:09:25

标签: android xml checkbox android-view

我按如下方式创建了一个自定义复选框xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/checkbox_selected_glow" android:state_focused="true" android:state_pressed="true" android:state_checked="true"/>
    <item android:drawable="@drawable/checkbox_selected_glow" android:state_focused="false" android:state_pressed="true" android:state_checked="true"/>
    <item android:drawable="@drawable/checkbox_selected" android:state_focused="false" android:state_pressed="false" android:state_checked="true"/>
    <item android:drawable="@drawable/checkbox_deselected_glow" android:state_focused="true" android:state_pressed="true" android:state_checked="false"/>
    <item android:drawable="@drawable/checkbox_deselected_glow" android:state_focused="false" android:state_pressed="true" android:state_checked="false"/>
    <item android:drawable="@drawable/checkbox_deselected" android:state_focused="false" android:state_pressed="false" android:state_checked="false"/>
</selector>

并在布局中实现:

<CheckBox
      android:layout_width="30dp"
      android:layout_height="30dp"
      android:layout_gravity="center_vertical"
      android:paddingRight="10dp"
      android:button="@null"
      android:background="@drawable/custom_checkbox"/>

效果很好并且当用户触摸它时,触摸它的用户会做出反应,传递到按下状态,并在用户松开触摸时进入选定/取消选择状态。

此CheckBox与TextView中的某些文本相关联,并且都包含在LinnearLayout中。

我希望只要用户按下LinnearLayout上的任何位置,就会激活CheckBox的按下状态。

是否只有xml方法可以执行此操作?

如果没有,我必须在LinnearLayout上覆盖哪些方法以编程方式使CheckBox对LinnearLayout的任何部分的触摸作出反应?

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情:

        LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
        final CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
        linearLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                checkBox.onTouchEvent(event);
                return true;
            }
        });