I am having trouble applying a gradient background to a LinearLayout.
This should be relatively simple from what I have read but it just doesn\'t seem to work. For r
Try removing android:gradientRadius="90". Here is one that works for me:
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<gradient
android:startColor="@color/purple"
android:endColor="@color/pink"
android:angle="270" />
</shape>
In XML Drawable File:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient android:angle="90"
android:endColor="#9b0493"
android:startColor="#38068f"
android:type="linear" />
</shape>
</item>
</selector>
In your layout file: android:background="@drawable/gradient_background"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_background"
android:orientation="vertical"
android:padding="20dp">
.....
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<gradient
android:angle="90"
android:startColor="@color/colorPrimary"
android:endColor="@color/colorPrimary"
android:centerColor="@color/white"
android:type="linear"/>
<corners android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topRightRadius="10dp"
android:topLeftRadius="10dp"/>
Change color values in the array
val gradientDrawable = GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
intArrayOf(Color.parseColor("#008000"),
Color.parseColor("#ADFF2F"))
);
gradientDrawable.cornerRadius = 0f;
//Set Gradient
linearLayout.setBackground(gradientDrawable);
Result
My problem was the .xml extension was not added to the filename of the newly created XML file. Adding the .xml extension fixed my problem.
Ok I have managed to solve this using a selector. See code below:
main_header.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:orientation="horizontal"
android:background="@drawable/main_header_selector">
</LinearLayout>
main_header_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="90"
android:startColor="#FFFF0000"
android:endColor="#FF00FF00"
android:type="linear" />
</shape>
</item>
</selector>
Hopefully this helps someone who has the same problem.