Android实现多个TextView同时显示跑马灯效果

  最近被一个页面弄得很蛋疼,这个页面比较小,需要显示较长的文案时无法显示完全,于是很自然地想到了TextView中的marquee —— 跑马灯效果,可是Android执行跑马灯效果需要控件获取焦点,当某一控件requestFocus()时,会将其他控件的焦点抢去,这就导致了同一时间只能有一个控件获取焦点。那么,如果让多个控件同时获取并持有焦点呢?或者说,“欺骗”Android系统,让它以为多个控件都持有焦点,即每个控件都在焦点状态。

  通过上述分析,问题转化为如何让多个控件同时处于焦点状态,这就需要重写TextView的部分方法,达到“欺骗”Android系统的目的,这样每个控件requestFocus()之后,均让自己处于焦点状态,并且不可被剥夺焦点,就可以达到多个控件同时“持有”焦点了,代码如下:

 1 public class MarqueeTextView extends TextView
 2 {
 3     public MarqueeTextView(Context context)
 4     {
 5         this(context, null);
 6     }
 7     
 8     public MarqueeTextView(Context context, AttributeSet attrs)
 9     {
10         super(context, attrs);
11         
12         setFocusable(true);
13         setFocusableInTouchMode(true);
14         
15         setSingleLine();
16         setEllipsize(TextUtils.TruncateAt.MARQUEE);
17         setMarqueeRepeatLimit(-1);
18     }
19     
20     public MarqueeTextView(Context context, AttributeSet attrs, int defStyle)
21     {
22         super(context, attrs, defStyle);
23         
24         setFocusable(true);
25         setFocusableInTouchMode(true);
26         
27         setSingleLine();
28         setEllipsize(TextUtils.TruncateAt.MARQUEE);
29         setMarqueeRepeatLimit(-1);
30     }
31 
32     @Override
33     protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect)
34     {
35         if (focused)
36         {
37             super.onFocusChanged(focused, direction, previouslyFocusedRect);
38         }
39     }
40     
41     @Override
42     public void onWindowFocusChanged(boolean focused)
43     {
44         if (focused)
45         {
46             super.onWindowFocusChanged(focused);
47         }
48     }
49     
50     @Override
51     public boolean isFocused()
52     {
53         return true;
54     }
55 }

  由于常规执行跑马灯的属性:android:focusable="true"、android:focusableInTouchMode="true"、android:singleLine="true"、android:ellipsize="marquee"

在代码中均已设置,故引用此控件时,无需添加上述4个属性。

posted @ 2013-04-19 20:16  热气球  阅读(2535)  评论(0编辑  收藏  举报