Search code examples
androidxmlandroid-studiokotlingradient

Set gradient color for text in Android Studio with Kotlin language


I have a text and I want to set a gradient color as its foreground. May I do it in XML?

Or should I do it in an activity? I am programming with Kotlin in Android Studio.

File activity_main.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFFF"
        android:gravity="center"
        android:text="Text Color is Gradient"
        android:textColor="#000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

File gradient.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <gradient
        android:angle="90"
        android:centerColor="#555994"
        android:endColor="#b5b6d2"
        android:startColor="#555994"
        android:type="linear" />

    <corners
        android:radius="0dp"/>

</shape>

My activity is this:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }
}

Solution

  • In order to set the gradient as Textview text color, you have to use textshader with parsing gradients color. You can customise the colors as of your requirement.

     val paint = textView.paint
            val width = paint.measureText(textView.text.toString())
            val textShader: Shader = LinearGradient(0f, 0f, width, textView.textSize, intArrayOf(
                Color.parseColor("#F97C3C"),
                Color.parseColor("#FDB54E"),
                /*Color.parseColor("#64B678"),
                Color.parseColor("#478AEA"),*/
                Color.parseColor("#8446CC")
            ), null, Shader.TileMode.REPEAT)
    
            textView.paint.setShader(textShader)
    

    Image