问题
I'm having an issue coloring a custom button. For some reason, it seems like no matter what coloring change I want to apply (text or background) the button remains the same.
I notice the button.xml
has the desired color and the right shape though it doesn't appear the button background-color
property on the activity
the button from an 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" />
custome button shape
<?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>
回答1:
If you are using material components (which is probably the case if this is a relatively new project) then you style the Button
in another way:
<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>
Things to notice are:
style="@style/Widget.MaterialComponents.Button"
android:textColor="@color/white"
app:backgroundTint="#FF0000"
(would be@color/redAdobeXD
in your case)app:cornerRadius="50dp"
There is no need for an extra xml and setting that on the button etc. (only in more custom cases).
You can read more about available options on the ContainedButton here
来源:https://stackoverflow.com/questions/65202859/having-an-issue-coloring-custome-xml-button