自定义TextView跑马灯

本篇主要介绍TextView的可控制跑马灯效果实现。

Android自带的TextView添加几个属性就可以实现跑马灯效果,大概是这样  

        android:ellipsize="marquee" 
        android:focusable="true" 
        android:focusableInTouchMode="true"    

就实现了TextView获取焦点时出现跑马灯效果。

本篇要实现的是一种不用获取焦点并且可以控制跑马灯开始和结束的方法。

1、主要利用void android.view.View.scrollTo(int x, int y)方法在后台不断scroll来实现文字移动效果。

在runnable中的run方法中调用scrollTo(currentScrollX,0)来移动文字,增加文字位置currentScrollX+=2,然后postDelayed(this, 5)再次进入到run方法中调用scrollTo(currentScrollX,0)。

 1        currentScrollX += 2;
 2             scrollTo(currentScrollX, 0); 
3
postDelayed(this, 5);

加上获取文字宽度停止控制以及从文本框右方出现后如下:

 1 public void run() {
 2         if (!isMeasure) {// 文字宽度只需获取一次就可以了
 3             getTextWidth();            
 4             isMeasure = true;
 5         }
 6         Log.i("不吃早饭","run getwidth:"+this.getWidth()+" textwidth:"+textWidth);
 7 
 8         if(this.getWidth() < textWidth) {
 9             currentScrollX += 2;
10             scrollTo(currentScrollX, 0);
11             if (isStop) {
12                 Log.i("不吃早饭", "isStop");
13                 return;
14             }
15             if (getScrollX() >= textWidth ) {
16                 Log.i("不吃早饭", "scrollTo");
17                 currentScrollX = -this.getWidth();
18                 scrollTo(currentScrollX, 0);
19                 // return;
20             }
21             postDelayed(this, 5);
22         }
23     }

其中this.getWidth() < textWidth用来判断文字宽度是否大于文本框宽度。获取文字宽度代码:

1 private void getTextWidth() {
2         Paint paint = this.getPaint();
3         String str = this.getText().toString();
4         textWidth = (int) paint.measureText(str);
5     }

注:获取文字宽度要在measure之后,因此要在run方法中。

下面是控制移动的方法:

 1 // 开始滚动
 2     public void startScroll() {
 3         invalidate();
 4         Log.i("不吃早饭","getwidth:"+this.getWidth()+" textwidth:"+textWidth);
 5         isStop = false;
 6         this.removeCallbacks(this);
 7         Log.i("不吃早饭", "startScroll");
 8         post(this);
 9     }
10 
11     // 停止滚动
12     public void stopScroll() {
13         isStop = true;
14         scrollTo(0, 0);
15         currentScrollX = -2;
16     }
17 
18     // 从头开始滚动
19     public void startFor0() {
20         currentScrollX = -2;
21         startScroll();
22     }

小demo链接:http://pan.baidu.com/s/1o61F1z0

posted @ 2015-01-17 16:03  不吃早饭好不好  阅读(526)  评论(0编辑  收藏  举报