有时候在xml中写的跑马灯效果不滚动:原因有以下
Android系统中TextView实现跑马灯效果,必须具备以下几个条件:
1、android:ellipsize=”marquee”
2、TextView必须单行显示,即内容必须超出TextView大小
3、TextView要获得焦点才能滚动(如果还不行,就要用自定义的TextView控件中重写isFocused()返回true就行【方法代码在下面的AlwaysMarqueeTextView 类】,但是遇到新问题就是界面有多个这样的控件显示时当弹出Dialog后这些自定义的TextView控件就会失去焦点,跑马灯效果又变成“...”的形式了,当Dialog消失之后又恢复正常)
XML代码:
android:ellipsize="marquee", android:singleLine="true"
Java代码:
mTVText.setText("哼唱接撒砥砺风节雷锋精神http://orgcent.com/,很长很长很长很长很长很长的数据");
mTVText.setSingleLine(true);
mTVText.setEllipsize(TruncateAt.MARQUEE);
PS: TextView.setHorizontallyScrolling(true); //让文字可以水平滑动
TextView还可以设置跑马灯效果的滚动次数,如下:
XML代码设置:
android:marqueerepeatlimit="1"。1代表1次,-1代表无限循环。
Java代码设置:
mTVText.setMarqueeRepeatLimit(-1);
总结一下跑马灯的实现效果,网上比较流行的有两种,测试过了都可以实现文字滚动效果,建议使用第一种,因为可以更好地控制文字滚动速度、样式、字体等属性,第二种方法,还没有找到控制的方法!
第一种:
控件类:AutoScrollTextView 继承了TextView并做了一些修改,实现了宽度的判断,文本自动滚动及开始和停止滚动等功能。
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class AutoScrollTextView extends TextView implements OnClickListener {
public final static String TAG = AutoScrollTextView.class.getSimpleName();
private float textLength = 0f;//文本长度
private float viewWidth = 0f;
private float step = 0f;//文字的横坐标
private float y = 0f;//文字的纵坐标
private float temp_view_plus_text_length = 0.0f;//用于计算的临时变量
private float temp_view_plus_two_text_length = 0.0f;//用于计算的临时变量
public boolean isStarting = false;//是否开始滚动
private Paint paint = null;//绘图样式
private String text = "";//文本内容
public AutoScrollTextView(Context context) {
super(context);
initView();
}
public AutoScrollTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public AutoScrollTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
private void initView()
{
setOnClickListener(this);
}
public void init(WindowManager windowManager)
{
paint = getPaint();
text = getText().toString();
textLength = paint.measureText(text);
viewWidth = getWidth();
if(viewWidth == 0)
{
if(windowManager != null)
{
Display display = windowManager.getDefaultDisplay();
viewWidth = display.getWidth();
}
}
step = textLength;
temp_view_plus_text_length = viewWidth + textLength;
temp_view_plus_two_text_length = viewWidth + textLength * 2;
y = getTextSize() + getPaddingTop();
}
@Override
public Parcelable onSaveInstanceState()
{
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.step = step;
ss.isStarting = isStarting;