当我们的textView一行不够显示需要显示的内容时,而又不能两行显示,这时候就需要跑马灯的形式来滚动显示,本文讲述的是横向滚动,纵向滚动还在研究中。下面将放一些主要代码供参考。
首页布局文件
android:id="@+id/test"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#339320"
android:ellipsize="marquee"
android:singleLine="true"
android:text="!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
android:textColor="#000000"
android:textSize="20dp" >
android:ellipsize=”marquee”
android:singleLine=”true”这两个属性必须要有的
然后java代码
这里用到了自定义的MarqueeText,需要将代码复制到项目中,里面的属性你可以自己定义达到你想要的效果,
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 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 setText(CharSequence text, BufferType type) {
super.setText(text, type);
this.isMeasure = false;
}
@Override
public void run() {
currentScrollX += 1;// 滚动速度
scrollTo(currentScrollX, 0);
if (isStop) {
return;
}
if (getScrollX() >= textWidth) {
scrollTo(-this.getWidth(), 0);
currentScrollX = -this.getWidth();
}
postDelayed(this, 10);
}
public void startScroll() {
isStop = false;
this.removeCallbacks(this);
post(this);
}
public void stopScroll() {
currentScrollX = 0;
isStop = true;
}
public void startFor0() {
currentScrollX = 0;
startScroll();
}
}
转载时请注明出处及相应链接,本文永久地址:https://blog.yayuanzi.com/13431.html
微信打赏
支付宝打赏
感谢您对作者abel的打赏,我们会更加努力! 如果您想成为作者,请点我