Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

讓 TextView 跑馬燈效果持續滾動的技巧

編輯:初階開發

原理說明

TextView 本身就自帶跑馬燈(marquee)能力,只要把顯示模式設成跑馬燈、設定滾動次數即可。但問題在於:跑馬燈要真正動起來,這個 TextView 必須先取得焦點。所以我們得想辦法讓它「假裝」永遠有焦點,才能持續滾動。

做法:改寫 isFocused

在自己包裡新增一個類別並繼承 TextView,然後覆寫 isFocused()。這個方法預設在取得焦點時回傳 true、失去焦點回傳 false,而跑馬燈正是靠它來判斷是否要啟動,因此我們讓它永遠回傳 true:

public class AlwaysMarqueeTextView extends TextView {
三個建構子分別是 (Context)、(Context, AttributeSet)、(Context, AttributeSet, int defStyle),各自呼叫 super 即可;接著:

@Override
public boolean isFocused() { return true; }

在版面配置中使用

於 layout XML 裡放入這個自訂檢視(寫法就是完整類別名稱):

<com.examples.AlwaysMarqueeTextView
android:id="@+id/AMTV1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="1"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:marqueeRepeatLimit="marquee_forever"
android:ellipsize="marquee"
android:background="@android:color/transparent"/>

關鍵屬性說明

ellipsize:決定文字過長時的顯示方式。start 把省略號放開頭、end 放結尾、middle 放中間,而 marquee 則是以跑馬燈方式橫向移動顯示。

marqueeRepeatLimit:在 ellipsize 設為 marquee 時,決定重複滾動的次數;設成 marquee_forever 代表無限次。

focusable:顧名思義就是能否取得焦點;而 focusableInTouchMode 則是觸控滑動時能否取得焦點。

組合檢視時的陷阱

把兩個 TextView 放進 LinearLayout 時,若焦點被外層的 LinearLayout 搶走,內層 TextView 就拿不到焦點,跑馬燈自然動不了——即使你也幫 TextView 設了 android:focusable="true" 一樣沒用。這時的解法是替 LinearLayout 加上 android:addStatesFromChildren 屬性,並把 TextView 的 focusable 設為 true 即可。

addStatesFromChildren 的官方說明是:Sets whether this ViewGroup's drawable states also include its children's drawable states(讓這個 ViewGroup 的 drawable 狀態一併納入子元素的狀態)。理解這句話,就能明白為什麼它能解決焦點被搶的問題。

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