package com.example.textedittext.utils;
import java.util.ArrayList;
import java.util.List;
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 = 0;// 初始滚动的位置
private int firstScrollX = 0;
private boolean isStop = false;
private int textWidth;
private int mWidth = 0; // 控件宽度
//text每次滚动长度
private int speed = 2;
//text两次滚动时间间隔 ms
private int delayed = 8;
private int endX; // 滚动到哪个位置
private boolean isFirstDraw = true; // 当首次或文本改变时重置
//text一次滚动完成后,多长时间启动第二次滚动
private int delayAgain =1000 ;
private List<String> list =new ArrayList<String>();
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 onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isFirstDraw) {
getTextWidth();
firstScrollX = getScrollX(); // 起始位置不一定为0,改变内容后会变,需重新赋值
currentScrollX = firstScrollX;
mWidth = this.getWidth();
//endX = firstScrollX + textWidth - mWidth / 2;//字体滚动到一半的时候就从头滚动
endX = firstScrollX + textWidth;//字体滚完整个屏幕后再从头滚动
isFirstDraw = false;
}
}
// 每次滚动几点
public void setSpeed(int sp) {
speed = sp;
}
// 滚动间隔时间,毫秒
public void setDelayed(int delay) {
delayed = delay;
}
/**
* 设置滚动的list 内容
* @param list
*/
public void setList(List<String> list){
/*if(list!=null&&list.size()!=0){
this.list = list;
setText(list.get(0));
}
*/
}
/**
* 获取文字宽度
*/
private void getTextWidth() {
Paint paint = this.getPaint();
String str = this.getText().toString();
textWidth = (int) paint.measureText(str);
}
@Override
public void run() {
long start=System.currentTimeMillis();
currentScrollX += 1;// 滚动速度,每次滚动几点
scrollTo(currentScrollX, 0);
// 从头开始
if (currentScrollX > endX) {
// scrollTo(0, 0);
// currentScrollX = 0; //原文重置为0,发现控件所放的位置不同,初始位置不一定为0
scrollTo(-mWidth, 0);
currentScrollX = -mWidth;
postDelayed(this, delayed);
if(list.size()!=0){
int current = list.indexOf(getText().toString());
if(current+1<list.size()){
setText(list.get(current+1));
}else{
setText(list.get(0));
}
}
} else {
postDelayed(this, delayed);
}
long end=System.currentTimeMillis();
if (isStop){
try {
isStop=false;
Thread.sleep(4000);
}catch (Exception e){
}
}else {
if (end - start < 10) {
try {
Thread.sleep(10 - (end - start));
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (currentScrollX == 0) {
isStop = true;
}
}
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
}
// 开始滚动
public void startScroll() {
isStop = false;
this.removeCallbacks(this);
postDelayed(this, 1000);
}
// 停止滚动
public void stopScroll() {
isStop = true;
}
// 从头开始滚动
public void startFor0() {
currentScrollX = 0;
startScroll();
}
}
自己处理的TextView跑马
最新推荐文章于 2022-06-11 10:24:54 发布