How to create horizontal gradient for AppCompatButton text color in android

I wanted to create a horizontal text color gradient for mine AppCompatButton. I was able to perform a vertical gradient of text color on

val signInBtn = view.findViewById<AppCompatButton>(R.id.btn_sign_in)
val textShader = LinearGradient(0f, 0f, 0f, signInBtn.textSize,
            ContextCompat.getColor(context, R.color.gradient_start),
            ContextCompat.getColor(context, R.color.gradient_end), TileMode.CLAMP)
signInBtn.paint.shader = textShader

I tried changing the values โ€‹โ€‹of x2, but nothing works. Any help would be appreciated.

here is my xml layout button

<android.support.v7.widget.AppCompatButton
    android:id="@+id/btn_sign_in"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="@dimen/big"
    android:layout_marginStart="@dimen/big"
    android:layout_marginTop="@dimen/big"
    android:background="@color/white"
    android:text="@string/sign_in"
    android:textAllCaps="false"
    android:fadingEdge="horizontal"
    android:scrollHorizontally="true"
    android:textColor="@color/white"/>
+4
source share
1 answer

If you want to do this in XML than Zephyr is perfect, but if you want to do it dynamically, you can try something like

Button theButton = (Button)findViewById(R.id.thebutton);
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
    @Override
    public Shader resize(int width, int height) {
        LinearGradient lg = new LinearGradient(0, 0, 0, theButton.getHeight(),
            new int[] { 
                Color.LIGHT_GREEN, 
                Color.WHITE, 
                Color.MID_GREEN, 
                Color.DARK_GREEN }, //substitute the correct colors for these
            new float[] {
                0, 0.45f, 0.55f, 1 },
            Shader.TileMode.REPEAT);
         return lg;
    }
};
PaintDrawable p = new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);
theButton.setBackgroundDrawable((Drawable)p);

Not sure, but in my case it shows the gradient horizontally

0
source

Source: https://habr.com/ru/post/1686318/


All Articles