一、問(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)看。