Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create horizontal gradient for text color of AppCompatButton in android

I wanted to generate horizontal text color gradient for my AppCompatButton. I was able to accomplish the vertical text color gradient by

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've tried changing the x2 values, but nothing seems to work. Any help would be appreciated.

here is my button xml layout

<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"/>
like image 412
Samuel Robert Avatar asked Nov 08 '22 16:11

Samuel Robert


1 Answers

If you want to do this in XML than "Zephyr" approch is perfect suit this but if want want to do this dynamically you can try some thing 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 show gradient horizontally

like image 100
sushant gosavi Avatar answered Nov 14 '22 23:11

sushant gosavi