Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android TextView 跑馬燈效果的實現方法

編輯:關於 Android 程式設計

本文分享一個實現 TextView 跑馬燈(文字滾動)效果的實例,供感興趣的讀者參考。

核心思路是通過自定義一個 TextView 子類,重寫 isFocused() 方法並恆返回 true,讓控件始終處於「獲得焦點」的狀態,從而觸發跑馬燈滾動:

 public class MyTextView extends TextView{ public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public MyTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } public MyTextView(Context context) { super(context); // TODO Auto-generated constructor stub } @Override public boolean isFocused() { // TODO Auto-generated method stub return true; //must be return true; } } 

然後在 XML 佈局中使用這個自定義控件,並配置相關屬性:

 <packagename.MyTextView android:id="@+id/my_textview" android:layout_width="400px" android:layout_height="35px" android:singleLine="true" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:textSize="22sp"/> 

其中 android:ellipsize="marquee" 設置為跑馬燈模式,android:marqueeRepeatLimit="marquee_forever" 表示無限次循環滾動,android:singleLine="true" 則保證文字單行顯示。這樣配置之後,文字便能實現持續滾動的效果。

希望本文所述對大家的 Android 開發有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved