我有一个GradientTextView类,它扩展了AppCompatTextView
public class GradientTextView extends android.support.v7.widget.AppCompatTextView {
public GradientTextView(Context context) {
super(context);
}
public GradientTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GradientTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
//Setting the gradient if layout is changed
if (changed) {
getPaint().setShader(new LinearGradient(0, 0, getWidth(), getHeight(),
ContextCompat.getColor(getContext(), R.color.colorStart),//Red Color
ContextCompat.getColor(getContext(), R.color.colorEnd),// Blue Color
Shader.TileMode.CLAMP));
}
}
}
这是渐变文本视图的xml
<package.GradientTextView
android:id="@+id/textLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login."
android:textStyle="bold"
android:padding="4dp"
android:layout_marginStart="8dp"/>
我想改变梯度颜色DINAMICAL。
用程序改变颜色的最好方法是什么?
public class GradientTextView extends android.support.v7.widget.AppCompatTextView {
int colorStart = ContextCompat.getColor(getContext(), R.color.colorStart);
int colorEnd = ContextCompat.getColor(getContext(), R.color.colorEnd);
public GradientTextView(Context context) {
super(context);
}
public GradientTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public GradientTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
//Setting the gradient if layout is changed
if (changed) {
getPaint().setShader(new LinearGradient(0, 0, getWidth(), getHeight(), colorStart, colorEnd,
Shader.TileMode.CLAMP));
}
}
public void setGradientColors(int colorStart, int colorEnd) {
this.colorStart = colorStart;
this.colorEnd = colorEnd;
// this forces view redrawing
invalidate();
}
}
代码
textView.setGradientColors(ContextCompat.getColor(this,R.color.ncolorEnd, R.color.ncolorStart));
错误