效果:
先自定义 MyTextView:
代码语言:javascript
复制public class MyTextView extends android.support.v7.widget.AppCompatTextView {
private Paint mPaint = null;
private int mViewWidth = 0;
private LinearGradient mLinearGradient;
private Matrix mGradientMatrix;
private int mTranslate;
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mViewWidth == 0) {
mViewWidth = getMeasuredWidth();
if( mViewWidth > 0 ){
mPaint = getPaint();
mLinearGradient = new LinearGradient(0, 0, mViewWidth, 0, new int[]{
Color.BLUE,
0xffffffff,
Color.BLUE
}, null, Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
mGradientMatrix = new Matrix();
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mGradientMatrix != null){
mTranslate = mViewWidth/5;
if (mTranslate > 2*mViewWidth){
mTranslate = -mViewWidth;
}
mGradientMatrix.setTranslate(mTranslate, 0);
mLinearGradient.setLocalMatrix(mGradientMatrix);
postInvalidateDelayed(100);
}
}
}
在布局文件中添加:
代码语言:javascript
复制