android - 添加具有默认外观但更改背景颜色的按钮

标签 android material-design android-button material-components material-components-android

我有一个线性布局,我在其中以编程方式添加按钮。我希望这些按钮具有按钮的默认外观和行为( float 、阴影等),但我想更改主要颜色。

这是我试过的

val newContext = ContextThemeWrapper(baseContext, R.style.PrimaryColoredButton)
val button = Button(newContext)
button.text = "test"

我的 styles.xml 包含以下代码

<style name="PrimaryColoredButton" parent="Base.Widget.AppCompat.Button.Colored">
    <item name="colorButtonNormal">@color/colorAccent</item>
    <item name="colorControlHighlight">@color/colorPrimary</item>
</style>

然而,这并没有改变我的按钮的颜色,而是给出了默认颜色。

enter image description here

最佳答案

你可以使用 android:backgroundTint="@android:color/white" 但遗憾的是,它只能在 Android API 21+ 中使用

如果您想更改 Android API 级别低于 21 的按钮。 您可以使用 AppCompatButton 使用应用程序命名空间而不是 android 的 backgroundTint。所以它会像这样 app:backgroundTint="@android:color/white"

例如:

<android.support.v7.widget.AppCompatButton
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Button"
app:backgroundTint="@android:color/white" />

关于android - 添加具有默认外观但更改背景颜色的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57522652/

相关文章:

java - 为什么这个语句在java中运行良好但在android中运行不佳?

c# - Multidex Xamarin Maps android 问题

java - 必须释放分数忍者才能保存分数吗?

Android Circular 确定 ProgressBar

html - Material Design Lite - 卡片支持文本在网格内时不会随着更大的卡片展开

c# - 如何在 Android 使用内置 Material Design 时对 Xamarin.Forms iOS 应用程序进行样式化

java - 如何使用十六进制颜色值更改按钮文本颜色?

java - 如何使用 HttpUrlConnection 正确执行 POST?

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

android - 如何将按钮对齐到 ListView 的底部,即使在删除行后仍粘在底部?