android Textview 循环滚动效果

public class MyView extends android.support.v7.widget.AppCompatTextView implements View.OnClickListener {
    public MyView(Context context) {
        super(context);
        initView();}

    public MyView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView();

    }

    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();

}

private float textLength = 0f;//文本长度
private float viewWidth = 0f;
private float step = 0f;//文字的横坐标
private float y = 0f;//文字的纵坐标
private float temp_view_plus_text_length = 0.0f;//用于计算的临时变量
private float temp_view_plus_two_text_length = 0.0f;//用于计算的临时变量
public boolean isStarting = false;//是否开始滚动
private Paint paint = null;//绘图样式
private String text = "";//文本内容

private void initView()
{
    setOnClickListener(this);
}
public void init(WindowManager windowManager)
{
    paint = getPaint();
    text = getText().toString();
    textLength = paint.measureText(text);
    viewWidth = getWidth();
    if(viewWidth == 0)
    {
        if(windowManager != null)
        {
            Display display = windowManager.getDefaultDisplay();
            viewWidth = display.getWidth();
        }
    }
    step = textLength;
    temp_view_plus_text_length = viewWidth + textLength;
    temp_view_plus_two_text_length = viewWidth + textLength*2;
    y = getTextSize() + getPaddingTop();
}
@Override
public void onDraw(Canvas canvas) {
    canvas.drawText(text, step-textLength-textLength, y, paint);
    if(!isStarting)
    {
        return;
    }
    step += 1.5;//0.5为文字滚动速度。
    if(step > temp_view_plus_two_text_length){
        step = textLength;
    }
    invalidate();

}

你可能感兴趣的:(android Textview 循环滚动效果)