自定义后材质复选框样式

bei*_*rad 3 android android-custom-view material-components material-components-android androidx

我的自定义复选框 ( MyCheckbox) 已从 扩展androidx.appcompat.widget.AppCompatCheckBox,但默认样式不适用于它。

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    ...
    <item name="android:checkboxStyle">@style/CheckboxTheme</item>
    <item name="checkboxStyle">@style/CheckboxTheme</item>
</style>

<style name="CheckboxTheme" parent="@style/Widget.AppCompat.CompoundButton.CheckBox">
     <!-- for example try to change background -->
    <item name="android:background">@color/colorPrimary</item>
</style>
Run Code Online (Sandbox Code Playgroud)

但在预览和运行时没有改变任何东西。

另外,我迁移了 MaterialComponent (从 扩展com.google.android.material.checkbox.MaterialCheckBox)版本:

com.google.android.material:material:1.1.0-beta01
Run Code Online (Sandbox Code Playgroud)

并用于@style/Widget.MaterialComponents.CompoundButton.CheckBox样式。但没有改变。

注意: 当我提到每个实例的样式时,此问题就修复了:

            <com.something.MyCheckBox
                android:id="@+id/ch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="some thing"
                style="@style/CheckboxTheme"
             />
Run Code Online (Sandbox Code Playgroud)

但我想为此类的所有实例设置此样式。 你可以帮帮我吗?

Gab*_*tti 7

MaterialCheckBoxMaterial Components 库提供的使用主题checkboxStyle中定义的属性。
只需覆盖此属性即可全局定义应用程序中的样式:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
   <!-- .... -->
   <item name="checkboxStyle">@style/MyCheckBox</item>
</style>
Run Code Online (Sandbox Code Playgroud)

如果你想自定义颜色,可以使用materialThemeOverlay样式中的属性:

<style name="MyCheckBox" parent="@style/Widget.MaterialComponents.CompoundButton.CheckBox">
   <item name="materialThemeOverlay">@style/ThemeOverlay.CheckBox</item>
</style>
Run Code Online (Sandbox Code Playgroud)

和:

  <style name="ThemeOverlay.CheckBox" parent="">
    <item name="colorSecondary">@color/....</item>   <!-- checked -->
    <item name="colorOnSurface">@color/.....</item>  <!-- unchecked -->
  </style>
Run Code Online (Sandbox Code Playgroud)

您还可以使用以下方法将样式应用于单个复选框:

<com.google.android.material.checkbox.MaterialCheckBox
    style="@style/MyCheckBox"
    ..>
Run Code Online (Sandbox Code Playgroud)

作为替代方案,您也可以在布局中使用android:theme,但它不能全局工作。

<com.google.android.material.checkbox.MaterialCheckBox
    ...
    android:theme="@style/ThemeOverlay.CheckBox"/>
Run Code Online (Sandbox Code Playgroud)

只是一个注释。
colorTint 选择器是在MaterialCheckBox代码中以编程方式定义的。您还可以定义自定义 colorTint 选择器,buttonTint在自定义样式中添加该属性。在这种情况下,上面定义的颜色将被忽略。