【Android】跑马灯效果(文字滚动)


所谓跑马灯效果就是当文字超过控件所能容纳的空间时,在控件内滚动的效果。

要实现这样的效果需要在布局文件中加上:

  1. Android:singleLine=”true”  
  2. android:ellipsize=”marquee”  
  3. android:focusableInTouchMode=”true”  
  4. android:focusable=”true”  
需要注意的是:layout_width=”"要写成固定值,不能是wrap_content或者fill_parent,而且要比text长度长。另外还可以设置滚动的次数android:marqueeRepeatLimit=”";
android:marqueeRepeatLimit=”marquee_forever”表示一直滚动。

但是这种跑马灯只有在控件获得焦点时在能滚动,要想让控件里的内容一直滚动就要定制该控件,重写里面的三个方法:

  1. package cn.etzmico.marqueetest;  
  2.   
  3. import android.content.Context;  
  4. import android.graphics.Rect;  
  5. import android.util.AttributeSet;  
  6. import android.widget.Button;  
  7.   
  8. public class MarqueeButton extends Button {  
  9.   
  10. public MarqueeButton(Context context, AttributeSet attrs) {  
  11. super(context, attrs);  
  12. // TODO Auto-generated constructor stub   
  13. }  
  14. @Override  
  15. protected void onFocusChanged(boolean focused, int direction,  
  16. Rect previouslyFocusedRect) {  
  17. // TODO Auto-generated method stub   
  18. if(focused)  
  19. super.onFocusChanged(focused, direction, previouslyFocusedRect);  
  20. }  
  21.   
  22. @Override  
  23. public void onWindowFocusChanged(boolean hasWindowFocus) {  
  24. // TODO Auto-generated method stub   
  25. if(hasWindowFocus)  
  26. super.onWindowFocusChanged(hasWindowFocus);  
  27. }  
  28. @Override  
  29. public boolean isFocused() {  
  30. return true;  
  31. }  
  32. }  

下面就是要在布局文件里使用这个控件了:

  1. <cn.easymobi.application.memorytest.MarqueeButton  
  2. android:layout_width=”216dip”  
  3. android:layout_height=”wrap_content”  
  4. android:id=”@+id/btSecond”  
  5. android:background=”@drawable/button_test2″  
  6. android:layout_marginTop=”15dip”  
  7. android:text=”@string/calculate”  
  8. android:ellipsize=”marquee”  
  9. android:gravity=”center”  
  10. android:textColor=”@color/white”  
  11. android:textStyle=”bold”  
  12. android:focusable=”true”  
  13. android:marqueeRepeatLimit=”marquee_forever”  
  14. android:focusableInTouchMode=”true”  
  15. android:scrollHorizontally=”true”  
  16. android:singleLine=”true”  
  17. android:paddingLeft=”50dip”  
  18. android:paddingRight=”50dip”  
  19. android:textSize=”20dip”  
  20. />  

相关内容