1. 程式人生 > >自定義TextView跑馬燈效果可控制啟動/停止/速度

自定義TextView跑馬燈效果可控制啟動/停止/速度

package com.xuhui.customrolllight;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;


public class MarqueeText extends TextView implements Runnable {
private int currentScrollX; // 當前滾動的位置
private boolean isStop = false;
private int textWidth;
private boolean isMeasure = false;


public MarqueeText(Context context) {
super(context);
}


public MarqueeText(Context context, AttributeSet attrs) {
super(context, attrs);
}


public MarqueeText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}


@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
currentScrollX = this.getWidth();
}


protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (!isMeasure) {
getTextWidth();// 文字寬度只需要獲取一次就可以了
isMeasure = true;
}
}


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


@Override
/*
* public void run() { currentScrollX-=2;//滾動速度.+號表示往左邊-
* scrollTo(currentScrollX,0); if(isStop){ return; }
* if(getScrollX()<=-(this.getWidth())){ scrollTo(textWidth,0);
* currentScrollX=textWidth; } postDelayed(this, 5); }
*/
public void run() {
currentScrollX += 2;// 滾動速度.+號表示往左邊-
scrollTo(currentScrollX, 0);
if (isStop) {
return;
}
if (getScrollX() >= (textWidth)) {
currentScrollX = -(this.getWidth());// 當前出現的位置
}
postDelayed(this, 1);
}
/*(public void run() {


//currentScrollX += 3;// 滾動速度.+號表示往左邊-
//scrollTo(currentScrollX, 0);


if (textWidth>this.getWidth()) {
currentScrollX += 3;// 滾動速度.+號表示往左邊-
scrollTo(currentScrollX, 0);
}
if (getScrollX() >= (textWidth)) {
// scrollTo(this.getWidth(),0);
currentScrollX = -(this.getWidth());// 當前出現的位置
}
postDelayed(this, 5);
})這裡面實現的是沒有省略號的效果。文字沒有超出框的長度就不滾,超出就滾*/

// 開始滾動
public void startScroll() {
isStop = false;
this.removeCallbacks(this);
post(this);
}


// 停止滾動
public void stopScroll() {
isStop = true;
}


// 從頭開始滾動
public void startFromHead() {
currentScrollX = 0;
startScroll();
}
}