編輯:關於 Android 程式設計
桌面小工具(AppWidget)裡的歌曲名稱如果太長,預設會被截斷或只滾動一次就停。Android 的 TextView 要跑跑馬燈,必須同时满足「獲得焦點」與「ellipsize 設為 marquee」等條件,而在 AppWidget 場景下焦點條件很難自然成立。解法是客製一個永遠回報有焦點的 TextView。
在 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。
./mk update-api
接著重新編譯整個工程並下載至手機,讓新的 View 類別進入 framework。
編輯 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 推回手機覆蓋原檔即可看到效果。
ellipsize 設為 marquee、singleLine 為 true,並在資料填入後明確呼叫 setSelected(true) 或 requestFocus() 即可。marqueeRepeatLimit 除了 marquee_forever,也可以指定有限次數;一直滾動在视觉上容易干扰,短標題其實保持截斷更清爽。update-api 不可省略,否則 App 端會找不到新的 View 類別。
一篇帶你透透徹徹認識 Android N 的重量級更新
今年三月,Google 破天荒地提前半年發布了 Android N 開發者預覽版。作為一名自詡稱職的「谷粉」,我卻沒能第一時間嘗鮮——畢竟去年今日刷 Android M
Android 教學:Android 調用 JNI 方法及完整程式碼
Android 調用 JNI 方法及程式碼 JNI:Java Native Interface,用來實現 Java 與 C/C++ 的互通。 本文記錄在 Android
Android 自訂 Chronometer 實現簡訊驗證碼秒表倒計時功能
本文為大家分享透過 Chronometer 實現倒計時功能,Android 提供了實現按秒計時的 API,供各位參考,具體內容如下。一、自訂 ChronometerVie
Android 圖片輪播廣告:滑動切換標題與焦點小圓點的實現
在許多應用的首頁,都會看到可以左右滑動、自動循環的圖片輪播效果,底部往往還帶有隨頁面切換而變化的標題與指示小圓點。本文以谷歌 v4 包中的 ViewPager 為基礎,一