问题
I can't set the background of a FAB with a gradient. The background of the FAB shows a black
color
My mainActivtiy xml file is given below
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
tools:context=".MainActivity">
<com.google.android.material.bottomappbar.BottomAppBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:backgroundTint="@color/colorPrimary"
app:menu="@menu/bottom_nav"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/button_gradient"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
My custom gradient file is as follows
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<gradient
android:angle="90"
android:startColor="#E12160"
android:endColor="#3F5CC8" />
<size
android:width="56dp"
android:height="56dp" />
</shape>
</item>
<item
android:left="10dp"
android:right="10dp">
<shape android:shape="line">
<stroke
android:width="2dp"
android:color="#ffffff" />
</shape>
</item>
<item
android:left="10dp"
android:right="10dp">
<rotate
android:fromDegrees="90">
<shape android:shape="line">
<stroke
android:width="2dp"
android:color="#ffffff" />
</shape>
</rotate>
</item>
</layer-list>
I am getting the output as follows
My gradient xml looks like below
回答1:
After researching a bit I came to know that in the FAB attributes the background is set to the default color if not specified by the user. If the the background we specify is not a color value, then automatically the tint
value is set to black(not available). So change it toapp:tint="@null"
. This makes sure that our custom background gets visible
回答2:
use the foreground
attribute to render your drawable above all of the content in the view
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:foreground="@drawable/button_gradient"/>
来源:https://stackoverflow.com/questions/61733369/how-to-set-the-background-of-a-fab-as-a-gradient