gpt4 book ai didi

android - 自定义后 Material 复选框样式

转载 作者:行者123 更新时间:2023-11-30 04:54:00 24 4
gpt4 key购买 nike

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

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

最佳答案

Material Components库提供的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>

与:

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

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

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

作为替代方案,您还可以在布局中使用 android:theme,但它在全局范围内不起作用。

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

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

关于android - 自定义后 Material 复选框样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59520384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com