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

5

我想为我的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

我已经尝试更改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"/>
1个回答

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);

我不确定,但在我的情况下它显示水平渐变。


我不是想改变背景颜色,我想改变按钮文本颜色的渐变。 - Samuel Robert
@zephyr 再次请仔细阅读问题,我需要水平渐变而不是垂直的。 - Samuel Robert
@Samuel Robert,请看我的修改过的回答,希望有所帮助。 - zephyr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接