如果对显示没有特别要求可以直接使用属性就能做到,在布局文件中将TextView属性设置一下:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈"
android:textSize="17sp" />
//设置为跑马灯显示
android:ellipsize="marquee"
//获取焦点
android:focusable="true"
//可以通过toucth来获得focus
android:focusableInTouchMode="true"
//设置重复的次数
android:marqueeRepeatLimit="marquee_forever"
//单行显示文字
android:singleLine="true"
使用属性设置要注意:这种属性配置只能在TextView获取焦点的时候跑马灯才会滚动,一旦失去焦点跑马灯就不会滚动
如果没有特殊需求的话使用这种还是简单方便的,但是如果需要跑马灯一直在滚动的话单纯的这样是做不到的,于是上网查了各种资料,大多数都是重定义TextView控件,重写onFocusChanged方法,里面什么也不做,将super的调用直接屏蔽,但经过测试这种还是不行,如果在dialog弹出时,显示效果和TextView属性配置是一样的结果,但是如果再在自定义的控件类中重写onWindowFocusChanged,将super方法屏蔽掉,这样就达到效果了,就算是dialog弹出也不影响跑马灯的显示效果,话不多说,先看图片:
下面看看具体代码,自定义的TextView(MarqueeText):
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;
public class MarqueeText extends TextView {
public MarqueeText(Context context) {
super(context);
}
public MarqueeText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MarqueeText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//重写isFocused方法,让其一直返回true
public boolean isFocused() {
return true;
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
}
}
看到很多博客都是自定义 MarqueeText,但是没有重写onWindowFocusChanged,当dialog弹出时,跑马灯就直接停掉了
在布局文件中的使用:
<com.test.view.MarqueeText
android:id="@+id/redmin_delete_tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center_vertical"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈"/>
编码的路还很长,我们一起走