編輯:關於 Android 程式設計
公告欄、活動通知那種一行行往上翻滾的效果,開源實現可以參考原作者項目:https://github.com/sfsheng0322/MarqueeView 。本文從源碼角度拆解它的實現原理。
public class MarqueeView extends ViewFlipper {
private Context mContext;
private List<String> notices;
private boolean isSetAnimDuration = false;
private OnItemClickListener onItemClickListener;
private int interval = 2000;
private int animDuration = 500;
private int textSize = 14;
private int textColor = 0xffffffff;
private int gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
private static final int TEXT_GRAVITY_LEFT = 0, TEXT_GRAVITY_CENTER = 1, TEXT_GRAVITY_RIGHT = 2;
public MarqueeView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
this.mContext = context;
if (notices == null) {
notices = new ArrayList<>();
}
TypedArray typedArray = getContext().obtainStyledAttributes(attrs,
R.styleable.MarqueeViewStyle, defStyleAttr, 0);
interval = typedArray.getInteger(R.styleable.MarqueeViewStyle_mvInterval, interval);
isSetAnimDuration = typedArray.hasValue(R.styleable.MarqueeViewStyle_mvAnimDuration);
animDuration = typedArray.getInteger(R.styleable.MarqueeViewStyle_mvAnimDuration, animDuration);
if (typedArray.hasValue(R.styleable.MarqueeViewStyle_mvTextSize)) {
textSize = (int) typedArray.getDimension(R.styleable.MarqueeViewStyle_mvTextSize, textSize);
textSize = DisplayUtil.px2sp(mContext, textSize);
}
textColor = typedArray.getColor(R.styleable.MarqueeViewStyle_mvTextColor, textColor);
int gravityType = typedArray.getInt(R.styleable.MarqueeViewStyle_mvGravity, TEXT_GRAVITY_LEFT);
switch (gravityType) {
case TEXT_GRAVITY_CENTER:
gravity = Gravity.CENTER;
break;
case TEXT_GRAVITY_RIGHT:
gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
break;
}
typedArray.recycle();
setFlipInterval(interval);
Animation animIn = AnimationUtils.loadAnimation(mContext, R.anim.anim_marquee_in);
if (isSetAnimDuration) animIn.setDuration(animDuration);
setInAnimation(animIn);
Animation animOut = AnimationUtils.loadAnimation(mContext, R.anim.anim_marquee_out);
if (isSetAnimDuration) animOut.setDuration(animDuration);
setOutAnimation(animOut);
}
// 根據公告字符串啟動輪播
public void startWithText(final String notice) {
if (TextUtils.isEmpty(notice)) return;
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
getViewTreeObserver().removeGlobalOnLayoutListener(this);
startWithFixedWidth(notice, getWidth());
}
});
}
// 根據公告字符串列表啟動輪播
public void startWithList(List<String> notices) {
setNotices(notices);
start();
}
// 根據寬度和公告字符串啟動輪播
private void startWithFixedWidth(String notice, int width) {
int noticeLength = notice.length();
int dpW = DisplayUtil.px2dip(mContext, width);
int limit = dpW / textSize;
if (dpW == 0) {
throw new RuntimeException("Please set MarqueeView width !");
}
if (noticeLength <= limit) {
notices.add(notice);
} else {
int size = noticeLength / limit + (noticeLength % limit != 0 ? 1 : 0);
for (int i = 0; i < size; i++) {
int startIndex = i * limit;
int endIndex = ((i + 1) * limit >= noticeLength ? noticeLength : (i + 1) * limit);
notices.add(notice.substring(startIndex, endIndex));
}
}
start();
}
// 啟動輪播
public boolean start() {
if (notices == null || notices.size() == 0) return false;
removeAllViews();
for (int i = 0; i < notices.size(); i++) {
final TextView textView = createTextView(notices.get(i), i);
final int finalI = i;
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(finalI, textView);
}
}
});
addView(textView);
}
if (notices.size() > 1) {
startFlipping();
}
return true;
}
// 創建 ViewFlipper 下的 TextView
private TextView createTextView(String text, int position) {
TextView tv = new TextView(mContext);
tv.setGravity(gravity);
tv.setText(text);
tv.setTextColor(textColor);
tv.setTextSize(textSize);
tv.setTag(position);
return tv;
}
public int getPosition() {
return (int) getCurrentView().getTag();
}
public List<String> getNotices() {
return notices;
}
public void setNotices(List<String> notices) {
this.notices = notices;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
void onItemClick(int position, TextView textView);
}
}
MarqueeView 繼承自 ViewFlipper,理解了它也就理解了跑馬燈。

ViewFlipper 的機制非常簡單:把添加到裡面的子 View 按順序定時切換顯示,同一時刻只有一個子 View 可見,其餘全部設為 GONE。

成員變量的含義一目了然:上下文、公告集合、是否自定義動畫時長、點擊監聽、輪播間隔(默認 2000ms)、動畫時長(默認 500ms)、字號、顏色,以及默認靠左垂直居中,最後是三個表示文字位置的常量。
構造方法裡調用 init 完成屬性解析,對應的 styleable 聲明如下:
<declare-styleable name="MarqueeViewStyle">
<attr name="mvInterval" format="integer|reference"/>
<attr name="mvAnimDuration" format="integer|reference"/>
<attr name="mvTextSize" format="dimension|reference"/>
<attr name="mvTextColor" format="color|reference"/>
<attr name="mvGravity">
<enum name="left" value="0"/>
<enum name="center" value="1"/>
<enum name="right" value="2"/>
</attr>
</declare-styleable>
解析流程逐行看:
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MarqueeViewStyle, defStyleAttr, 0);
先拿到屬性集合,取出 mvInterval,默認值 2000。
isSetAnimDuration = typedArray.hasValue(R.styleable.MarqueeViewStyle_mvAnimDuration);
判斷用戶有沒有自定義動畫時長。
if (typedArray.hasValue(R.styleable.MarqueeViewStyle_mvTextSize)) {
textSize = (int) typedArray.getDimension(R.styleable.MarqueeViewStyle_mvTextSize, textSize);
textSize = DisplayUtil.px2sp(mContext, textSize);
}
若設置了自定義字號,取出後把 px 轉成 sp;接著解析控件位置,最後記得回收:
typedArray.recycle();
setFlipInterval(interval) 設置滾屏間隔,單位毫秒。
Animation animIn = AnimationUtils.loadAnimation(mContext, R.anim.anim_marquee_in); if (isSetAnimDuration) animIn.setDuration(animDuration); setInAnimation(animIn); Animation animOut = AnimationUtils.loadAnimation(mContext, R.anim.anim_marquee_out); if (isSetAnimDuration) animOut.setDuration(animDuration); setOutAnimation(animOut);
這是一進一出的切換動畫。
startWithText(String notice) 對外暴露,內部通過 getViewTreeObserver 測出控件寬度後,調用 startWithFixedWidth(notice, getWidth()):
private void startWithFixedWidth(String notice, int width) {
int noticeLength = notice.length();
int dpW = DisplayUtil.px2dip(mContext, width);
int limit = dpW / textSize;
if (dpW == 0) {
throw new RuntimeException("Please set MarqueeView width !");
}
if (noticeLength <= limit) {
notices.add(notice);
} else {
int size = noticeLength / limit + (noticeLength % limit != 0 ? 1 : 0);
for (int i = 0; i < size; i++) {
int startIndex = i * limit;
int endIndex = ((i + 1) * limit >= noticeLength ? noticeLength : (i + 1) * limit);
notices.add(notice.substring(startIndex, endIndex));
}
}
start();
}
邏輯是:先把像素寬度換算成 dp,再除以字號得到每行能放多少字(limit)。字符串不超長就直接 add;超長則用除法加取餘算出總行數,然後循環截取每一行的首尾下標——末行如果越界就取到字符串末尾。最後 start() 開始播放。
public boolean start() {
if (notices == null || notices.size() == 0) return false;
removeAllViews();
for (int i = 0; i < notices.size(); i++) {
final TextView textView = createTextView(notices.get(i), i);
final int finalI = i;
textView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(finalI, textView);
}
}
});
addView(textView);
}
if (notices.size() > 1) {
startFlipping();
}
return true;
}
private TextView createTextView(String text, int position) {
TextView tv = new TextView(mContext);
tv.setGravity(gravity);
tv.setText(text);
tv.setTextColor(textColor);
tv.setTextSize(textSize);
tv.setTag(position);
return tv;
}
每一行都做成一個 TextView 並 add 進來,然後調用 startFlipping() 開始定時切換。後面剩下的就是點擊回調和公告集合的 get/set。
最後別忘了在佈局頂層加入:
xmlns:app="https://schemas.android.com/apk/res-auto"
以上就是本文的全部內容,希望對大家的學習有所幫助。
仿去哪兒首頁效果:用 Canvas、Matrix 與縮放動畫打造可點擊的功能方塊
第一張是進入頁面的樣子:頂部一個可滑動的 ViewPager,下面是一格格自定義的功能方塊 HomeButton。第二張是手指按下方塊時的狀態——方塊整體縮小,中間浮
WebView 兩大難題破解:重定向導致 goBack 失效與 JS 物件注入漏洞防範
第一部分:重定向讓 goBack() 失效 問題現場 初始頁面為 A,點擊某個連結跳到 B(https://xxx.com.cn/),而 B 又重定向到 C(https:
Android ViewPager 實現無限自動輪播:Adapter 改造與線程循環
很多 App 中都實現了類似引導頁的自動輪播,看到時便想到:只要在昨天的引導頁上改改程式碼就能實現輪播。其實大體上只需要加上一個線程循環執行就可以了。項目已同步至:htt
ContentObserver 實戰:跨應用監聽 ContentProvider 數據變化
ContentProvider 不只提供讀寫,還內建了「資料變了通知你」的能力,這正是 ContentObserver 存在的意義。掌握它之後,A 應用修改資料,B 應用