gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:48:29 25 4
gpt4 key购买 nike

以编程方式创建的按钮不遵循 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 显示。
我想知道为什么上述两种按钮创建方法的按钮样式不一致?

最佳答案

它们是不同的,因为您使用的是 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

关于android - 以编程方式创建的按钮不遵循主题的按钮样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67197434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com