以编程方式创建的按钮不遵循主题的按钮样式

时间:2021-04-21 14:01:43

标签: android button android-appcompat android-button android-theme

以编程方式创建的按钮不遵循 apptheme 中定义的 buttonStyle,但在 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>

这就是我以编程方式创建按钮的方式:

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

它显示为带有黑色文本颜色的默认灰色背景。

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

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

它工作正常,并以白色文本颜色和样式中指定的正确 backgroundTint 显示。

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

2 个答案:

答案 0 :(得分:2)

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

您可以使用:

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

enter image description here

答案 1 :(得分:0)

这应该可以解决问题

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

int buttonStyle = Button.Primary;
Button button = new Button(new ContextThemeWrapper(this, buttonStyle), null, buttonStyle);
相关问题