Android 繼承RadioButton 無(wú)法點(diǎn)擊

一、問(wèn)題描述

繼承RadioButton,實(shí)現(xiàn)一些自定義需求,示例:

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 中應(yīng)用:

<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>

然而,運(yùn)行之后,MyRadioBtn 是不響應(yīng)點(diǎn)擊事件的,點(diǎn)擊也無(wú)法進(jìn)行切換。

二、問(wèn)題解決

class MyRadioBtn @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = androidx.appcompat.R.attr.radioButtonStyle  // 關(guān)鍵點(diǎn)在這里
) : AppCompatRadioButton(context, attrs, defStyleAttr) {

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

這里的關(guān)鍵代碼如上注釋處,MyRadioBtn 的構(gòu)造函數(shù),defStyleAttr 參數(shù)的默認(rèn)值不能傳0,一定要傳一個(gè)style,可以自定義,這里直接用的androidx.appcompat 的style。

原因可能跟TextView 的onTouchEvent 處理有關(guān),暫時(shí)沒(méi)看。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容