Android 继承RadioButton 无法点击

一、问题描述

继承RadioButton,实现一些自定义需求,示例:

class MyRadioBtn @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatRadioButton(context, attrs, defStyleAttr) {

    override fun onDraw(canvas: Canvas) {
        // do something
        super.onDraw(canvas)
    }
}

在XML 中应用:

<RadioGroup
        android:id="@+id/gender_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <com.xxx.MyRadioBtn
            android:id="@+id/gender_male_btn"
            android:layout_width="@dimen/selection_button_height"
            android:layout_height="@dimen/selection_button_weight"
            android:background="@drawable/bg_select_gender"
            android:button="@null"
            android:checked="true"
            android:gravity="center"
            android:text="@string/gender_iam_male"
            android:textColor="?textColor1"
            android:textSize="24sp" />

        <com.xxx.MyRadioBtn
            android:id="@+id/gender_female_btn"
            android:layout_width="@dimen/selection_button_height"
            android:layout_height="@dimen/selection_button_weight"
            android:layout_marginTop="10dp"
            android:background="@drawable/bg_select_gender"
            android:button="@null"
            android:gravity="center"
            android:text="@string/gender_iam_female"
            android:textColor="?textColor1"
            android:textSize="24sp" />
</RadioGroup>

然而,运行之后,MyRadioBtn 是不响应点击事件的,点击也无法进行切换。

二、问题解决

class MyRadioBtn @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = androidx.appcompat.R.attr.radioButtonStyle  // 关键点在这里
) : AppCompatRadioButton(context, attrs, defStyleAttr) {

    override fun onDraw(canvas: Canvas) {
        // do something
        super.onDraw(canvas)
    }
}

这里的关键代码如上注释处,MyRadioBtn 的构造函数,defStyleAttr 参数的默认值不能传0,一定要传一个style,可以自定义,这里直接用的androidx.appcompat 的style。

原因可能跟TextView 的onTouchEvent 处理有关,暂时没看。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容