Android 以编程方式创建的按钮不';不要跟随主题';s按钮样式

Android 以编程方式创建的按钮不';不要跟随主题';s按钮样式,android,button,android-appcompat,android-button,android-theme,Android,Button,Android Appcompat,Android Button,Android Theme,以编程方式创建的按钮不遵循apptheme中定义的按钮样式,但以xml创建的按钮遵循它 下面是我的style.xml <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary&q

以编程方式创建的按钮不遵循apptheme中定义的按钮样式,但以xml创建的按钮遵循它

下面是我的style.xml

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="buttonStyle">@style/Button.Primary</item>
    </style>

    <style name="Button.Primary" parent="Widget.AppCompat.Button.Colored">
        <item name="textAllCaps">true</item>
        <item name="android:textColor">#fff</item>
        <item name="backgroundTint">@color/btn_bck</item>
    </style>
它显示为默认的灰色背景和黑色文本颜色

但是如果我在xml中使用按钮,比如:

<Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

它工作良好,显示为白色文本颜色和样式中指定的正确背景色


我想知道为什么上面两种按钮创建方法之间的按钮样式不一致?

这应该可以解决问题

int buttonStyle = R.style.Button.Primary;
Button button = new Button(this, null, buttonStyle);


它们是不同的,因为您使用的是
主题.AppCompat.*
主题。 使用此主题,布局中定义的
按钮
在运行时被
AppCompatButton
替换

您可以使用:

Button progBtn = new AppCompatButton(this);
progBtn.setText("Programmatic button");
LinearLayout layout = findViewById(R.id.container);
layout.addView(progBtn)

您使用的是
按钮
构造函数,它不包含任何样式化属性;你想要的是接受他们的人;编辑:它也没有继承默认按钮样式,因为您正在为
AppCompatButton
buttonStyle
vs
android:buttonStyle
)定义属性,但随后使用
按钮
哦,谢谢,我尝试使用
新按钮(这个,null,R.attr.buttonStyle)(虽然我不确定这是否是正确的使用方法),但它仍然没有像预期的那样工作。它确实应用了样式,但背景颜色不同。它使用颜色重音作为背景色。任何时候,对于“它使用颜色重音作为背景色”-这与我在第一条评论中的编辑的原因相同:样式使用AppCompat属性格式(
backgroundTint
而不是
android:backgroundTint
)实现,默认的
按钮不使用该按钮。您需要使用android样式声明(
android:xxxx
)或使用
AppCompatButton
instead@ShivamPokhriyal
new按钮(这个,null,R.attr.buttonStyle)
不起作用,因为它使用与属性
buttonStyle
定义的相同样式,但它是一个按钮,而不是
AppCompatButton
。这意味着实现是不同的。检查下面的答案。并感谢@Cruceo的编辑。这还不够。这样,您的
按钮
使用属性
按钮样式
定义的样式,但它不是布局中定义的
按钮
。通过这种方式,他们使用了一种不同的实现,这就解决了这个问题。谢谢!!:)
int buttonStyle = Button.Primary;
Button button = new Button(new ContextThemeWrapper(this, buttonStyle), null, buttonStyle);
Button progBtn = new AppCompatButton(this);
progBtn.setText("Programmatic button");
LinearLayout layout = findViewById(R.id.container);
layout.addView(progBtn)