如何在Android中为AppCompatButton的文本颜色创建水平渐变

Sam*_*ert 5 shader android button linear-gradients

我想为我的生成水平文本颜色渐变AppCompatButton。我能够通过完成垂直文本颜色渐变

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
Run Code Online (Sandbox Code Playgroud)

我曾尝试更改x2值,但似乎无济于事。任何帮助,将不胜感激。

这是我的按钮xml布局

<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"/>
Run Code Online (Sandbox Code Playgroud)

sus*_*vi 2

如果您想在 XML 中执行此操作,那么“Zephyr”方法非常适合此操作,但如果您想动态执行此操作,您可以尝试类似的操作

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);
Run Code Online (Sandbox Code Playgroud)

不确定,但就我而言,它显示水平渐变