【问题标题】:Android styling button with ContextThemeWrapper带有 ContextThemeWrapper 的 Android 样式按钮
【发布时间】:2019-03-25 08:52:14
【问题描述】:

我正在尝试在运行时使用 Button 元素填充表格,我正在尝试将styles.xml 中定义的样式应用到。

<style name="BlueButtonStyle">
    <item name="android:textSize">20sp</item>
    <item name="android:padding">15dp</item>
    <item name="android:layout_margin">5dp</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_weight">1</item>
    <item name="android:background">@drawable/gradient_button</item>
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:textAllCaps">false</item>
</style>

我已经在一些可以定义style="@style/BlueButtonStyle" 的静态按钮上使用了这种风格,所以我知道这种风格本身是有效的。它看起来像这样:

按钮是在这样的循环中生成的:

val contextWrapper = ContextThemeWrapper(context, R.style.BlueButtonStyle)
val btn = Button(contextWrapper).apply { text = "Unknown" }

但是,结果看起来不像它应该的样子:

#FFFFFF 的字体颜色已被应用,但没有别的。它也没有与无样式按钮相同的灰色背景。

如何正确设置以编程方式生成的按钮的样式?我希望避免膨胀 xml。解决方案应该向后兼容最低 android 6.0。

【问题讨论】:

  • BlueButtonStyle 不是主题。这是一种风格。 (我知道,这很令人困惑。)ContextThemeWrapper 需要一个主题。您需要将R.style 传递给您设置&lt;item name="android:buttonStyle"&gt;@style/BlueButtonStyle&lt;/item&gt; 的主题。您可能还想给BlueButtonStyle 一个父母,以照顾您没有在那里设置的所有属性;例如&lt;style name="BlueButtonStyle" parent="android:Widget.Material.Button"&gt;.

标签: android kotlin styles


【解决方案1】:

我不知道 kotlin,但在 Java 中,你可以这样做:

ContextThemeWrapper wrapper = new ContextThemeWrapper(this,R.style.BlueButtonStyle);
Button btn = new Button(wrapper, null, 0); // note this constructor
btn.setText("Unknown");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 2012-11-28
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多