Shi*_*yal 5 android button android-appcompat android-theme android-button
以编程方式创建的按钮不遵循应用程序主题中定义的按钮样式,但在 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>
Run Code Online (Sandbox Code Playgroud)
这就是我以编程方式创建按钮的方法:
Button progBtn = new Button(this);
progBtn.setText("Programmatic button");
LinearLayout layout = findViewById(R.id.container);
layout.addView(progBtn);
Run Code Online (Sandbox Code Playgroud)
它显示为默认的灰色背景和黑色文本颜色。
但如果我在 xml 中使用按钮,例如:
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
Run Code Online (Sandbox Code Playgroud)
它工作正常,并以白色文本颜色和样式中指定的正确背景色调显示。
我想知道为什么上面两种创建按钮的方法,按钮样式不一致?
它们是不同的,因为您使用的是Theme.AppCompat.*
主题。使用此主题,Button
布局中的定义在运行时被替换为AppCompatButton
.
您可以使用:
Button progBtn = new AppCompatButton(this);
progBtn.setText("Programmatic button");
LinearLayout layout = findViewById(R.id.container);
layout.addView(progBtn)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1886 次 |
最近记录: |