[英]Android styling button with ContextThemeWrapper
I'm trying to populate a table at run time with Button elements, which I'm trying to apply a style defined in styles.xml
to. 我试图在运行时使用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>
I'm already using this style on some static buttons where I'm able to define style="@style/BlueButtonStyle"
, so I know that the style itself works. 我已经在一些可以定义
style="@style/BlueButtonStyle"
静态按钮上使用了这种样式,因此我知道样式本身可以工作。 It looks like this: 看起来像这样:
Buttons are generated in a loop like this: 在这样的循环中生成按钮:
val contextWrapper = ContextThemeWrapper(context, R.style.BlueButtonStyle)
val btn = Button(contextWrapper).apply { text = "Unknown" }
However, the result doesn't look the way it should: 但是,结果看起来不应该这样:
The font color of #FFFFFF
has been applied, but nothing else. #FFFFFF
的字体颜色已应用,但没有其他设置。 It also doesn't have the same gray background that an unstyled button would have. 它也没有未样式按钮所具有的灰色背景。
How do I properly style a programmatically generated Button? 如何正确设置以编程方式生成的Button的样式? I was hoping to avoid having to inflate xml.
我希望避免不得不给xml充气。 Solution should be backwards compatible to min android 6.0.
解决方案应向后兼容Min android 6.0。
I don't know kotlin, but in Java, you could do like this: 我不了解kotlin,但是在Java中,您可以这样做:
ContextThemeWrapper wrapper = new ContextThemeWrapper(this,R.style.BlueButtonStyle);
Button btn = new Button(wrapper, null, 0); // note this constructor
btn.setText("Unknown");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.