具有ContextThemeWrapper的Android样式按钮 [英] Android styling button with ContextThemeWrapper

查看:90
本文介绍了具有ContextThemeWrapper的Android样式按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

<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"的静态按钮上使用了这种样式,因此我知道样式本身可以工作.看起来像这样:

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. 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:

已应用#FFFFFF的字体颜色,但仅此而已.它也没有没有样式的按钮具有相同的灰色背景.

The font color of #FFFFFF has been applied, but nothing else. It also doesn't have the same gray background that an unstyled button would have.

如何正确设置以编程方式生成的Button的样式?我希望避免不得不给xml充气.解决方案应向后兼容最低android 6.0.

How do I properly style a programmatically generated Button? I was hoping to avoid having to inflate xml. Solution should be backwards compatible to min android 6.0.

推荐答案

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

I don't know kotlin, but in Java, you could do like this:

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

这篇关于具有ContextThemeWrapper的Android样式按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆