1 public class AutoScrollTextView extends TextView implements Runnable {
2 private int currentScrollX;// 当前滚动的位置
3 private boolean isStop = false;
4 private int textWidth;
5 private boolean isMeasure = false;
6
7 public AutoScrollTextView(Context context) {
8 super(context);
9 }
10
11 public AutoScrollTextView(Context context, AttributeSet attrs) {
12 super(context, attrs);
13 }
14
15 public AutoScrollTextView(Context context, AttributeSet attrs, int defStyle) {
16 super(context, attrs, defStyle);
17 }
18
19 @Override
20 protected void onDraw(Canvas canvas) {
21 super.onDraw(canvas);
22 if (!isMeasure) {// 文字宽度只需获取一次就可以了
23 getTextWidth();
24 isMeasure = true;
25 }
26 }
27
28 /**
29 * 获取文字宽度
30 */
31 private void getTextWidth() {
32 Paint paint = this.getPaint();
33 String str = this.getText().toString();
34 textWidth = (int) paint.measureText(str);
35 }
36
37 @Override
38 public void run() {
39 currentScrollX -= 1;// 滚动速度
40 scrollTo(currentScrollX, 0);
41 if (isStop) {
42 return;
43 }
44 if (getScrollX() <= -(this.getWidth())) {
45 scrollTo(textWidth, 0);
46 currentScrollX = textWidth;
47 }
48 postDelayed(this, 5);
49 }
50
51 // 开始滚动
52 public void startScroll() {
53 isStop = false;
54 this.removeCallbacks(this);
55 post(this);
56 }
57
58 // 停止滚动
59 public void stopScroll() {
60 isStop = true;
61 }
62
63 // 从头开始滚动
64 public void startFor0() {
65 currentScrollX = 0;
66 startScroll();
67 }
68 }