歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 【Android】跑馬燈效果(文字滾動)

【Android】跑馬燈效果(文字滾動)

日期:2017/3/1 10:47:54   编辑:Linux編程

所謂跑馬燈效果就是當文字超過控件所能容納的空間時,在控件內滾動的效果。

要實現這樣的效果需要在布局文件中加上:

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

下面就是要在布局文件裡使用這個控件了:

  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. />
Copyright © Linux教程網 All Rights Reserved