为客户 xml 按钮着色时出现问题

Having an issue coloring custome xml button

我在为自定义按钮着色时遇到问题。出于某种原因,似乎无论我想应用什么颜色更改(文本或背景)按钮都保持不变。

我注意到 button.xml 具有所需的颜色和正确的形状,尽管它没有出现 activity[=15= 上的按钮 background-color 属性 ]

来自 activity

的按钮
   <Button
        android:id="@+id/button2"
        android:layout_width="162dp"
        android:layout_height="53dp"
        android:background="@drawable/button"
        android:text="@string/button"
        android:textAllCaps="false"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.132"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/messagTextView"
        app:layout_constraintVertical_bias="0.804" />

自定义按钮形状

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="50sp"/>
    <solid android:color="@color/redAdobeXD"/>
</shape>

如果您正在使用 material components(如果这是一个相对较新的项目,可能就是这种情况),那么您可以用另一种方式设置 Button 的样式:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".FirstFragment">

    <Button
        android:id="@+id/button"
        style="@style/Widget.MaterialComponents.Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="32dp"
        android:text="I am a Button!"
        android:textColor="@color/white"
        app:backgroundTint="#FF0000"
        app:cornerRadius="50dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

需要注意的事项是:

  • style="@style/Widget.MaterialComponents.Button"
  • android:textColor="@color/white"
  • app:backgroundTint="#FF0000"(在您的情况下为 @color/redAdobeXD
  • app:cornerRadius="50dp"

不需要额外的 xml 并在按钮等上设置它(仅在更多自定义情况下)。

您可以在 ContainedButton here

上阅读有关可用选项的更多信息