material checkbox style after customize

前端 未结 2 630
孤独总比滥情好
孤独总比滥情好 2021-01-20 08:25

My customized checkbox (MyCheckbox) has extended from androidx.appcompat.widget.AppCompatCheckBox, but the default styles don\'t apply to it.

相关标签:
2条回答
  • 2021-01-20 09:02

    According to this answer, I tried using ContextThemeWrapper to apply the style:

    class MyCheckbox @JvmOverloads constructor(context: Context,
                                            attrs: AttributeSet? = null,
                                            defStyle: Int = 0)
    : MaterialCheckBox(ContextThemeWrapper(context, R.style.CheckboxTheme), attrs, defStyle)
    
    0 讨论(0)
  • 2021-01-20 09:03

    The MaterialCheckBox provided by the Material Components library uses the checkboxStyle attribute defined in the theme.
    Just override this attribute to define globally the style in your app:

    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
       <!-- .... -->
       <item name="checkboxStyle">@style/MyCheckBox</item>
    </style>
    

    If you want to customize the color you can use the materialThemeOverlay attribute in the style:

    <style name="MyCheckBox" parent="@style/Widget.MaterialComponents.CompoundButton.CheckBox">
       <item name="materialThemeOverlay">@style/ThemeOverlay.CheckBox</item>
    </style>
    

    with:

      <style name="ThemeOverlay.CheckBox" parent="">
        <item name="colorSecondary">@color/....</item>   <!-- checked -->
        <item name="colorOnSurface">@color/.....</item>  <!-- unchecked -->
      </style>
    

    You can also apply the style to the single checkbox using:

    <com.google.android.material.checkbox.MaterialCheckBox
        style="@style/MyCheckBox"
        ..>
    

    As alternative you can also use the android:theme in the layout, but it doesn't work globally.

    <com.google.android.material.checkbox.MaterialCheckBox
        ...
        android:theme="@style/ThemeOverlay.CheckBox"/>
    

    Just a note.
    The colorTint selector is defined programmatically in the MaterialCheckBox code. You can also define a custom colorTint selector adding the buttonTint attribute in your custom style. In this case the colors defined above are ignored.

    0 讨论(0)
提交回复
热议问题