Search code examples
javaandroidgradientbackground-color

How to set gradient color from complete transparency to dark in android?


I have an imageview and a cardview elevated on top of it. The cardview contains multiple views inside it.

I want to set a background color to cardview such that its startcolor should make the initial part of the imageview behind it to be visible at a transparency rate of 30% and the cardview should become darker and darker and black at the end.

This is what I have tried so far:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
    android:startColor="#80000000"
    android:endColor="#FF000000"
    android:angle="270"
    android:dither="true"
    />
</shape>

This doesn't make my imageview visible.I have explored many SOF posts but wasn't able to reproduce what I want!

Any inputs are welcome and would be very helpful!!


Solution

  • Use this XML code

    <?xml version="1.0" encoding="utf-8"?>
    <shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#21293B"
        android:centerColor="#21293B00"
        android:endColor="#00000000"
        android:angle="90"/>
    </shape>
    

    put it as a background to a View, put that View above your ImageView

     <RelativeLayout
                android:id="@+id/player_layout"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">
    <ImageView
                android:id="@+id/shasha_poster"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:minHeight="500dp"
                android:scaleType="centerCrop"
                android:src="@drawable/placeholder"
                android:visibility="visible" />
    
    <View
                android:id="@+id/gradient"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/background_with_shadow2" />
     </RelativeLayout>