自定义TextView跑马灯

时间:2023-03-09 15:40:04
自定义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)。

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

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

 public void run() {
if (!isMeasure) {// 文字宽度只需获取一次就可以了
getTextWidth();
isMeasure = true;
}
Log.i("不吃早饭","run getwidth:"+this.getWidth()+" textwidth:"+textWidth); if(this.getWidth() < textWidth) {
currentScrollX += 2;
scrollTo(currentScrollX, 0);
if (isStop) {
Log.i("不吃早饭", "isStop");
return;
}
if (getScrollX() >= textWidth ) {
Log.i("不吃早饭", "scrollTo");
currentScrollX = -this.getWidth();
scrollTo(currentScrollX, 0);
// return;
}
postDelayed(this, 5);
}
}

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

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

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

下面是控制移动的方法:

 // 开始滚动
public void startScroll() {
invalidate();
Log.i("不吃早饭","getwidth:"+this.getWidth()+" textwidth:"+textWidth);
isStop = false;
this.removeCallbacks(this);
Log.i("不吃早饭", "startScroll");
post(this);
} // 停止滚动
public void stopScroll() {
isStop = true;
scrollTo(0, 0);
currentScrollX = -2;
} // 从头开始滚动
public void startFor0() {
currentScrollX = -2;
startScroll();
}

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