最近在自己的音乐播放器项目中要加入跑马灯效果,于是便研究了下。跑马灯效果是 TextView 自带的一个属性,使用 TextView 来实现单个、多个跑马灯效果比较简单。
1. 单个跑马灯效果
这种比较简单,只需要在布局文件中加入几个属性就可以了:
| 12
 3
 4
 5
 6
 
 | <TextViewandroid:ellipsize="marquee"
 android:focusable="true"
 android:focusableInTouchMode="true"
 android:marqueeRepeatLimit="marquee_forever"
 android:singleLine="true" />
 
 | 
2. 多个跑马灯效果
在同一个 layout 中,两个 TextView 如果都设置了焦点,只有后一个会处于 focused 的状态,这个时候需要写一个类来继承 TextView,稍作修改即可:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 
 | public class MarqueeView extends TextView {public MarqueeView(Context context) {
 this(context, null);
 }
 
 public MarqueeView(Context context, AttributeSet attrs) {
 this(context, attrs, 0);
 }
 
 public MarqueeView(Context context, AttributeSet attrs, int defStyleAttr) {
 super(context, attrs, defStyleAttr);
 }
 
 @Override
 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
 super.onFocusChanged(true, direction, previouslyFocusedRect);
 }
 
 @Override
 public void onWindowFocusChanged(boolean hasWindowFocus) {
 super.onWindowFocusChanged(true);
 }
 
 @Override
 public boolean isFocused() {
 return true;
 }
 }
 
 | 
然后就可以在布局文件中使用了:
| 12
 3
 4
 
 | <MarqueeViewandroid:ellipsize="marquee"
 android:marqueeRepeatLimit="marquee_forever"
 android:singleLine="true" />
 
 | 
appwidget 比较特殊,它只支持几个固定的 view,所以就不能实现多个跑马灯效果,只能实现单个效果,不过和在普通 layout 中的实现稍微有所不同:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | <TextViewandroid:ellipsize="marquee"
 android:focusable="true"
 android:focusableInTouchMode="true"
 android:marqueeRepeatLimit="marquee_forever"
 android:singleLine="true">
 <requestFocus
 android:duplicateParentState="true"
 android:focusable="true"
 android:focusableInTouchMode="true"/>
 </TextView>
 
 | 
需要在 TextView 中加入 requestFocus 标签才可以实现跑马灯效果。