android的跑马灯效果

来源:互联网 发布:matlab按列归一化矩阵 编辑:程序博客网 时间:2024/05/17 06:20

在Android中TextView要实现跑马灯的效果,一般都是在xml文件中给TextView设置以下配置:

[html] view plain copy
  1. android:ellipsize="marquee"   
  2. android:focusable="true"   
  3. android:marqueeRepeatLimit="marquee_forever"   
  4. android:focusableInTouchMode="true"   
  5. android:scrollHorizontally="true"  
  6. android:singleLine="true"  

然后在java代码中,设置时,需要加上requestFocus方法,这样配置特别麻烦,而且在某些机型中,就算按照这样设置,如果在设置了文字之后,再改变文字的内容,或者期间做了其他操作,发现跑马灯效果失效了,没有再自动滚动。


所以重写了一个TextView,简化了配置,并且解决了失效的问题。

代码如下:


[java] view plain copy
  1. import android.content.Context;  
  2. import android.graphics.Rect;  
  3. import android.text.TextUtils.TruncateAt;  
  4. import android.util.AttributeSet;  
  5. import android.widget.TextView;  
  6.   

  7. public class ScrollingTextView extends TextView {  
  8.   
  9.     public ScrollingTextView(Context context, AttributeSet attrs, int defStyle) {  
  10.         super(context, attrs, defStyle);  
  11.         init();  
  12.     }  
  13.   
  14.     public ScrollingTextView(Context context, AttributeSet attrs) {  
  15.         super(context, attrs);  
  16.         init();  
  17.     }  
  18.   
  19.     public ScrollingTextView(Context context) {  
  20.         super(context);  
  21.         init();  
  22.     }  
  23.   
  24.     @Override  
  25.     protected void onFocusChanged(boolean focused, int direction,  
  26.             Rect previouslyFocusedRect) {  
  27.         if (focused)  
  28.             super.onFocusChanged(focused, direction, previouslyFocusedRect);  
  29.     }  
  30.   
  31.     @Override  
  32.     public void onWindowFocusChanged(boolean focused) {  
  33.         if (focused)  
  34.             super.onWindowFocusChanged(focused);  
  35.     }  
  36.   
  37.     @Override  
  38.     public boolean isFocused() {  
  39.         return true;  
  40.     }  
  41.   
  42.     private void init() {  
  43.         setEllipsize(TruncateAt.MARQUEE);// 对应android:ellipsize="marquee"  
  44.         setMarqueeRepeatLimit(-1);// 对应android:marqueeRepeatLimit="marquee_forever"  
  45.         setSingleLine();// 等价于setSingleLine(true)  
  46.     }  
  47. }  

在xml中,只需在xml文件中进行如下配置:
[html] view plain copy
  1. <com.demo.view.ScrollingTextView  
  2.     android:id="@+id/tv_name"  
  3.     android:layout_width="800px"  
  4.     android:layout_height="wrap_content"  
  5. />  

在java代码中,就正常使用就行,不用再重新写获取焦点的代码了。

0 0
原创粉丝点击