TextView自带有跑马灯效果, 但是在特殊场景下使用时会出现跑马灯效果失效的问题。如ListView / GridView等适配器控件使用时。
TextView设置跑马灯效果有两种方式:
TextView tv = new TextView(getContext());
tv.setSingleLine(true);
tv.setEllipsize(TextUtils.TruncateAt.MARQUEE);
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:singleLine="true"
android:focusable="true"
android:ellipsize="marquee"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"/>
<!--
造成无法正常显示跑马灯效果的原因有:
1). 当前TextView无焦点, 只有当前View获取到焦点才会有跑马灯效果。
2). android:marqueeRepeatLimit属性设置不正确, 该属性设置跑马灯效果循环次数。
-->
TextView和ListView配合使用时因为有很多的Adapter Item。当前TextView不一定有焦点, 即便有焦点也只有一个TextView会有跑马灯动画。没错, 原因就是因为TextView没有焦点。
那么如下思路可能会帮助你解决问题。
public class MarqueeTextView extends TextView {
public MarqueeTextView(Context context) {
super(context);
}
public MarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(true);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(true, direction, previouslyFocusedRect);
}
@Override
public boolean isFocused() {
return true;
}
}