以编程方式应用于Button时,样式无法完全发挥作用 [英] Style not working entirely when applied on Button programmatically
本文介绍了以编程方式应用于Button时,样式无法完全发挥作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的风格:
<style name="buttonQuestionStyle" parent="@style/Widget.AppCompat.Button.Colored">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">@color/white</item>
<item name="android:textSize">16sp</item>
<item name="android:padding">25dp</item>
<item name="android:layout_margin">10dp</item>
<item name="android:background">@color/questionButton</item>
</style>
这是我的代码:
Button btn = new Button(getActivity());
btn.setText(ojb.getText());
if (Build.VERSION.SDK_INT < 23) {
btn.setTextAppearance(getActivity(), R.style.buttonQuestionStyle);
} else {
btn.setTextAppearance(R.style.buttonQuestionStyle);
}
在应用程序中:
以编程方式显示如下按钮:
Programmatically button appears like this:
通过布局它起作用了.出现如下:
And via layout it worked. Appears like this:
这是我在XML布局中的代码:
Here is my code in the XML Layout:
<Button
android:text="Question"
style="@style/buttonQuestionStyle" />
所以...我不知道为什么会发生,以及如何解决它.
So... I dont know why it happens, and how fix it.
推荐答案
您可以在按钮的构造函数中传递ContextThemeWrapper
,对Button(context, attributeset, defStyle)
使用3个参数构造函数.
You can pass a ContextThemeWrapper
in constructor for button and use 3 arguments constructor for Button(context, attributeset, defStyle)
.
ContextThemeWrapper wrapper = new ContextThemeWrapper(this,R.style.buttonQuestionStyle);
Button btn = new Button(wrapper, null, 0); // note this constructor
btn.setText("some text");
这篇关于以编程方式应用于Button时,样式无法完全发挥作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文