Home > Mobile >  How can I limit the gradient in Android Studio?
How can I limit the gradient in Android Studio?

Time:10-22

I'm developing my first app in Android studio and I have some styles applied to it, and one of them is a gradient background but I want to limit it.

This is my actual view:

enter image description here

The graident goes from top to bottom perfectly, but I want the gradient to occupy 1/4 of the screen, how can I do it? I've been looking on the internet but I didn't find a solution. Up to the red line for example:

enter image description here

How can I do it?

This is my actual drawable:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape>
        <gradient
            android:angle="-90"
            android:startColor="#3cba92"
            android:endColor="#e6e9f0"
            />
    </shape>
</item>
</selector>

CodePudding user response:

Rather than modifying your drawable, why don't create an empty layout which has height as 1/4th of the screen and background as your drawable.

The rest of your code will remain as it is and should have no background.

For example, this can be done easily using a constraint layout as follows.

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity"
    android:weightSum="1"
    >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:background="@drawable/background_gradient"
        app:layout_constraintTop_toTopOf="parent"
         />

</androidx.constraintlayout.widget.ConstraintLayout>

Studio visual representation

  • Note : You can set the height programatically by measuring the screen size and dividing it by 4.
  • Related