import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.Display;
import android.view.WindowManager;
import android.widget.TextView;
public class MarqueeTextView extends TextView {
/**
* 文字長度
*/
private float textLength = 0f;
/**
* 滾動條長度
*/
private float viewWidth = 0f;
/**
* 文本x軸 的坐標
*/
private float tx = 0f;
/**
* 文本Y軸的坐標
*/
private float ty = 0f;
/**
* 文本當前長度
*/
private float temp_tx1 = 0.0f;
/**
* 文本當前變換的長度
*/
private float temp_tx2 = 0x0f;
/**
* 文本滾動開關
*/
private boolean isStarting = false;
/**
* 畫筆對象
*/
private Paint paint = null;
/**
* 顯示的文字
*/
private String text = "";
/**
* 文本滾動速度
**/
private float sudu;
public MarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 初始化自動滾動條,每次改變文字內容時,都需要重新初始化一次
*
* @param windowManager 獲取屏幕
* @param text 顯示的內容
* @param su 文字滾動的速度
*/
public void initScrollTextView(WindowManager windowManager, String text, float su) {
// 得到畫筆,獲取父類的textPaint
paint = this.getPaint();
// 得到文字
this.text = text;
this.sudu = su;
textLength = paint.measureText(text);// 獲得當前文本字符串長度
viewWidth = this.getWidth();// 獲取寬度return mRight - mLeft;
if (viewWidth == 0) {
// 獲取當前屏幕的屬性
Display display = windowManager.getDefaultDisplay();
viewWidth = display.getWidth();// 獲取屏幕寬度 viewWidth 是滾動的開始位置,需要修改的
// 可再此入手
}
tx = textLength;
temp_tx1 = viewWidth + textLength;
temp_tx2 = viewWidth + textLength * 2;// 自己定義,文字變化多少
// // 文字的大小+距頂部的距離
ty = this.getTextSize() + this.getPaddingTop();
}
/**
* 開始滾動
*/
public void starScroll() {
// 開始滾動
isStarting = true;
this.invalidate();// 刷新屏幕
}
/**
* 停止方法,停止滾動
*/
public void stopScroll() {
// 停止滾動
isStarting = false;
this.invalidate();// 刷新屏幕
}
/**
* 重寫onDraw方法
*/
@Override
protected void onDraw(Canvas canvas) {
if (isStarting) {
// A-Alpha透明度/R-Read紅色/g-Green綠色/b-Blue藍色
//paint.setARGB(255, 200, 200, 200);
canvas.drawText(text, temp_tx1 - tx, ty, paint);
tx += sudu;
// 當文字滾動到屏幕的最左邊
if (tx > temp_tx2) {
// 把文字設置到最右邊開始
tx = textLength;
}
this.invalidate();// 刷新屏幕
}
super.onDraw(canvas);
}
}
使用:
MarqueeTextView marqueeTextView = contentView.findViewById(R.id.five_text__view); marqueeTextView.initScrollTextView(getWindowManager(), "滾動文字", 1); marqueeTextView.setText(""); marqueeTextView.starScroll();