自定义后的材料复选框样式

问题描述 投票:1回答:2

我的自定义复选框(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>

但未在预览和运行时中进行任何更改。

此外,我也在MaterialComponent(从com.google.android.material.checkbox.MaterialCheckBox扩展)版本上迁移:

com.google.android.material:material:1.1.0-beta01

并且使用@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"
             />

但是我想为此类的所有实例设置此样式。您能帮我吗?

android android-custom-view androidx material-components-android
2个回答
0
投票

根据this answer,我尝试使用ContextThemeWrapper来应用样式:

class MyCheckbox @JvmOverloads constructor(context: Context,
                                        attrs: AttributeSet? = null,
                                        defStyle: Int = 0)
: MaterialCheckBox(ContextThemeWrapper(context, R.style.CheckboxTheme), attrs, defStyle)

0
投票

材料组件库提供的MaterialCheckBox使用主题中定义的checkboxStyle属性。只需覆盖此属性即可在您的应用程序中全局定义样式:

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

如果要自定义颜色,可以在样式中使用materialThemeOverlay属性:

<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="colorSurface">@color/....</item>
    <item name="colorOnSurface">@color/.....</item>
  </style>

只是一个音符。colorTint选择器在MaterialCheckBox代码中以编程方式定义。您还可以定义自定义colorTint选择器,并以自定义样式添加buttonTint属性。

或者,您也可以在布局中使用android:theme,但它不能在全局范围内使用。

<com.google.android.material.checkbox.MaterialCheckBox
    ...
    android:theme="@style/ThemeOverlay.CheckBox"/>
© www.soinside.com 2019 - 2024. All rights reserved.