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

讓音樂播放器 AppWidget 的歌曲名稱持續滾動顯示

編輯:關於 Android 程式設計

桌面小工具(AppWidget)裡的歌曲名稱如果太長,預設會被截斷或只滾動一次就停。Android 的 TextView 要跑跑馬燈,必須同时满足「獲得焦點」與「ellipsize 設為 marquee」等條件,而在 AppWidget 場景下焦點條件很難自然成立。解法是客製一個永遠回報有焦點的 TextView。

一、新增 AlwaysMarqueeTextView

在 frameworks/base/core/java/android/widget/ 下建立:

package android.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RemoteViews.RemoteView;

@RemoteView
public class AlwaysMarqueeTextView extends TextView {

    public AlwaysMarqueeTextView(Context context) {
        super(context);
    }

    public AlwaysMarqueeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AlwaysMarqueeTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

重點是 @RemoteView 標註(AppWidget 的布局只能使用支援遠端 Views 的元件)與覆寫 isFocused() 永遠回傳 true。

二、更新 API 並編譯 framework

./mk update-api

接著重新編譯整個工程並下載至手機,讓新的 View 類別進入 framework。

三、修改 Music 的 AppWidget 布局

編輯 packages/apps/Music/res/layout/album_appwidget.xml,把原本的 TextView:

<TextView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/appwidget_text"
    android:textStyle="bold"
    android:textSize="18sp"
    android:singleLine="true"
    android:fadingEdge="horizontal"
    android:fadingEdgeLength="10dip"
    android:ellipsize="none" />

換成自訂元件,並補上焦點與跑馬燈相關屬性:

<AlwaysMarqueeTextView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/appwidget_text"
    android:textStyle="bold"
    android:textSize="18sp"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:singleLine="true"
    android:fadingEdge="horizontal"
    android:fadingEdgeLength="10dip"
    android:ellipsize="marquee"
    android:marqueeRepeatLimit="marquee_forever" />

四、重新編譯 Music.apk 並替換

把新的 Music.apk 推回手機覆蓋原檔即可看到效果。

幾個實務提醒

  • 這套做法需要修改 framework 並完整編譯,屬於平台/改機層級的客製化,一般第三方 App 無法這麼做。
  • 若只想在自己的 App 內讓文字滾動,不需要客製 View:把 ellipsize 設為 marquee、singleLine 為 true,並在資料填入後明確呼叫 setSelected(true) 或 requestFocus() 即可。
  • marqueeRepeatLimit 除了 marquee_forever,也可以指定有限次數;一直滾動在视觉上容易干扰,短標題其實保持截斷更清爽。
  • 修改 framework 後 update-api 不可省略,否則 App 端會找不到新的 View 類別。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved