文字的跑马灯效果

来源:互联网 发布:实体店买到网络专供款 编辑:程序博客网 时间:2024/04/30 13:35

如何实现TextView的Marquee效果 

往往看到一些应用的标题栏中当标题超出时便会自动滚动

这篇文章要讲的就是如何去实现TextView的Marquee效果

其实TextView已经自带了如何实现滚动的属性

Xml代码  收藏代码
  1.  android:singleLine="true"  
  2. android:ellipsize="marquee"  
  3. android:marqueeRepeatLimit="marquee_forever"   

 通过上面的属性设置就能让TextView滚动起来。当然也可以通过代码去设置。


但是当设置完之后发现并没有滚动起来,原来TextView滚动的前提是这个空间必须要获得焦点。TextView需要必须处于focus状态。


在TextView的父类View中有一个方法isFocused(),系统通过这个方法去判断一个空间是否获得焦点。

所以我们就有了解决方案:

写一个子类继承TextView,重写isFocused()方法,直接返回true。当通过这个函数去判断TextView有没有获得焦点时,总是返回获得焦点于是我们的TextView就开始滚动起来了。代码很简单:

Java代码  收藏代码
  1.  public class AlwaysMarqueeTextView extends TextView {  
  2.   
  3.     /** 
  4.      * constructor 
  5.      * @param context Context 
  6.      */  
  7.     public AlwaysMarqueeTextView(Context context) {  
  8.           super(context);  
  9.     }  
  10.   
  11.     /** 
  12.      * constructor 
  13.      * @param context Context 
  14.      * @param attrs AttributeSet 
  15.      */  
  16.     public AlwaysMarqueeTextView(Context context, AttributeSet attrs) {  
  17.           super(context, attrs);  
  18.     }  
  19.   
  20.     /** 
  21.      * constructor 
  22.      * @param context Context 
  23.      * @param attrs AttributeSet 
  24.      * @param defStyle int 
  25.      */  
  26.     public AlwaysMarqueeTextView(Context context, AttributeSet attrs, int defStyle) {  
  27.           super(context, attrs, defStyle);  
  28.     }  
  29.   
  30.       
  31.     @Override  
  32.     public boolean isFocused() {  
  33.           return true;  
  34.     }  
  35.     } 
 

0 0
原创粉丝点击