实现效果:从屏幕右侧滚动字幕到左侧滚出,并循环滚动
实现方法:自定义 Texiview
public class MyTextView extends TextView {
//文字的内容
private String mText;
//文字的颜色
private int mTextColor;
//文字的大小
private float mTextS;
private float offX = 0f;//初始值
private float mStep = 0.5f;//偏移量
//画笔,用来绘画文字所用
private Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG );
private Rect mRect = new Rect();
/** 字幕滚动的速度 快,普通,慢 */
public static final int SCROLL_SLOW = 0;
public static final int SCROLL_NORM = 1;
public static final int SCROLL_FAST = 2;
public MyTextView(Context context) {
super( context );
setSingleLine(true);
}
public MyTextView(Context context, AttributeSet attr) {
super(context, attr);
setSingleLine(true }
/**
textview 初始化时执行,且只执行一次
mText:获取文字信息
mTextColor:获取当前文字颜色
mTextS:获取文字大小
**/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure( widthMeasureSpec, heightMeasureSpec );
mText=getText().toString();
mTextColor=getCurrentTextColor();
mTextS=getTextSize();
paint.setTextSize( mTextS );
paint.setColor( mTextColor );
paint.getTextBounds(mText, 0, mText.length(), mRect);
}
/**
每次重新变更文字时,要执行该方法
**/
public void setmText(){
mText=getText().toString();
paint.getTextBounds(mText, 0, mText.length(), mRect);
}
/**
开始绘字
**/
@Override
protected void onDraw(Canvas canvas) {
float x,y;
//getMeasuredWidth() 是指 texiview 的内容占据的实际宽度
x=getMeasuredWidth()-offX;
//getMeasuredHeight()是指 textview 的内容占据的实际高度
//descent:baseline 之下至字符最低处的距离
//ascent:baseline 之上至字符最高处的距离(是负数)
//paigao.descent()-paint.ascent()) 意思就是该字符的高度
y=getMeasuredHeight()/2+(paint.descent()-paint.ascent())/2;
//
canvas.drawText( mText,x,y,paint );
offX+=mStep;
//mRect.width() 是指最小字符串的宽度
if(offX>=getMeasuredWidth()+mRect.width()){
offX=0;
}
invalidate();//意思是重绘
}
/**
* 设置字幕滚动的速度
*/
public void setScrollMode(int scrollMod) {
if (scrollMod == SCROLL_SLOW) {
mStep = 0.5f;
} else if (scrol SCROLL_NORM) {
mStep = 1f;
}else {
mStep = 1.5f;
}
}
}
好了,自定义 Texiview 结束,现在是 MainActivity
/**初始化 Textview,这一步不可少**/
MyTextView myTextView=(MyTextView)findViewById( R.id.MyTextView );
/**设置字体颜色和大小,滚动速度**/
myTextView.setTextSize( 60 );
myTextView.setTextColor( Color.rgb( 253, 243, 6 ) );
myTextView.setScrollMode( MyTextView.SCROLL_FAST );
/**然后是设置文字**/
myTextView.setText( "这里是跑马灯滚动效果" );
myTextView.setmText();
下面是 XML 文件
<com.spencer.demo.MyTextView
android:id="@+id/MyTextView"
android:layout_width="0dp"
android:layout_height="0dp"
android:textColor="#FDF306"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/listview"/>
这就是自定义的 Textview 实现跑马灯的效果