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

Android TextView 跑馬燈橫向滾動效果實作教學

編輯:關於 Android 程式設計

在 Android 開發中,當 TextView 顯示的文字超出可用寬度時,我們往往希望文字能像跑馬燈一樣橫向滾動,把完整內容呈現給使用者。以下分享一個實際測試可行的做法。

先看效果圖:

一、自訂可取得焦點的 TextView

核心思路是讓 TextView 隨時處於「已取得焦點」的狀態,因為系統只有在控制項獲得焦點時才會啟動跑馬燈動畫。做法是繼承 TextView 並覆寫 isFocused() 方法,讓它永遠回傳 true:

 package com.example.shen.marqueedemo; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; /** * Created by shen on 2015/8/19. */ public class MarqueeTextView extends TextView { public MarqueeTextView(Context context) { super(context); } public MarqueeTextView(Context context, AttributeSet attrs) { super(context, attrs); } public MarqueeTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean isFocused(){ return true; } } 

二、在佈局中設定關鍵屬性

接著在 XML 佈局檔裡套用自訂的 TextView,並設定三個重點屬性:

android:singleLine="true" 單行顯示

android:ellipsize="marquee" 以跑馬燈方式呈現(橫向移動動畫)

android:marqueeRepeatLimit="marquee_forever" 持續循環滾動

   

只要這三個屬性搭配自訂的 MarqueeTextView,文字就能在可視範圍內自動滾動,是不是很簡單呢?

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