編輯:關於 Android 程式設計
專案裡需要一個類似公告欄的元件,現成的開源方案大多只支援單行顯示,於是只能自己動手。以下是在既有公告條 demo 基礎上擴充出來的多行向上滾動版本,新增了幾項實用能力:
・資料自動分頁顯示
・可設定左側 Drawable 小圖示
・手指觸摸時暫停、離開後恢復
・3D 翻滾進出動畫
效果預覽

package com.android.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.Transformation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
/**
* 公告滾動區
*
* @author 祁連山
* @version 1.0
* @date 2016-08-17
*/
public class RollingView extends FrameLayout implements OnClickListener {
private static final int ANIMATION_DURATION = 1000; // 預設動畫時長
private long mDuration = 3000; // 翻頁間隔
private int mTextColor = 0xff000000; // 文字顏色
private int mClickColor = 0xff0099ff; // 點擊後顏色
private float mTextSize = 14;
private int mTextPadding = 10;
private Paint mPaint;
private int mPageSize = 3; // 每頁條目數
private int mUpLimited = mPageSize;
private int mCurrentPage = 0;
private int mPageCount;
private int mLeftDrawable;
private List<LinearLayout> mRollingPages;
private AnimationSet mEnterAnimSet;
private AnimationSet mExitAnimSet;
private RollingRunnable mRunnable;
private Handler mHandler;
private onItemClickListener mClickListener;
private LayoutParams mFrameParams;
private LinearLayout.LayoutParams mLinearParams;
// 向上翻頁的進出動畫
private Rotate3dAnimation mEnterDownAnim;
private Rotate3dAnimation mExitUpAnim;
// 向下翻頁的進出動畫
private Rotate3dAnimation mEnterUpAnim;
private Rotate3dAnimation mExitDownAnim;
public RollingView(Context context) { this(context, null); }
public RollingView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.RollingView);
mTextSize = array.getDimension(R.styleable.RollingView_textSize, mTextSize);
mTextColor = array.getColor(R.styleable.RollingView_textColor, mTextColor);
array.recycle();
createEnterAnimation();
createExitAnimation();
mPaint = new TextPaint();
mHandler = new Handler(Looper.getMainLooper());
mEnterDownAnim = createAnim(-90, 0, true, true);
mExitUpAnim = createAnim(0, 90, false, true);
mEnterUpAnim = createAnim(90, 0, true, false);
mExitDownAnim = createAnim(0, -90, false, false);
}
private Rotate3dAnimation createAnim(float start, float end,
boolean turnIn, boolean turnUp) {
final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end, turnIn, turnUp);
rotation.setDuration(300);
rotation.setFillAfter(false);
rotation.setInterpolator(new AccelerateInterpolator());
return rotation;
}
public void setPageSize(int pageSize) { this.mPageSize = this.mUpLimited = pageSize; }
public void setDelayedDuration(long millionSeconds) { this.mDuration = millionSeconds; }
public void setEnterAnimation(AnimationSet animation) { mEnterAnimSet = animation; }
public void setExitAnimation(AnimationSet animation) { mExitAnimSet = animation; }
public void setTextPadding(int padding) { this.mTextPadding = padding; }
public void setClickColor(int color) { this.mClickColor = color; }
public void setLeftDrawable(int drawable) { this.mLeftDrawable = drawable; }
public void setOnItemClickListener(onItemClickListener clickListener) {
if (null == clickListener) return;
this.mClickListener = clickListener;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 未指定寬度時給個預設值
int exceptWidth = 300;
int exceptHeight = 0;
// 高度依字型實際高度計算,直接寫死 textSize 會因預設行距而顯得鬆散
if (MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY) {
if (mTextSize > 0) {
mPaint.setTextSize(mTextSize);
Paint.FontMetrics fm = mPaint.getFontMetrics();
exceptHeight = (int) (fm.bottom - fm.top);
}
}
int width = resolveSize(exceptWidth, widthMeasureSpec);
int height = resolveSize(exceptHeight, heightMeasureSpec);
setMeasuredDimension(width, height);
}
/** 綁定資料並自動分頁 */
public void setRollingText(List<String> array) {
if (null == array || array.isEmpty()) return;
this.removeAllViews();
if (mRollingPages == null) {
mRollingPages = new ArrayList<>();
}
mRollingPages.clear();
int quotient = array.size() / mPageSize;
int remainder = array.size() % mPageSize;
mPageCount = remainder == 0 ? quotient : quotient + 1;
for (int i = 0; i < mPageCount; i++) {
LinearLayout container = createContainer();
if (i == mPageCount - 1) {
mUpLimited = remainder == 0 ? mPageSize : remainder;
}
for (int n = 0; n < mUpLimited; n++) {
TextView textView = createTextView(array.get(mPageSize * i + n));
container.addView(textView);
}
mRollingPages.add(container);
this.addView(container);
}
mCurrentPage = 0;
mRollingPages.get(mCurrentPage).setVisibility(VISIBLE);
this.setVisibility(mRollingPages.get(mCurrentPage));
}
private LinearLayout createContainer() {
if (mFrameParams == null) {
mFrameParams = new LayoutParams(MATCH_PARENT, WRAP_CONTENT);
mFrameParams.gravity = Gravity.CENTER_VERTICAL;
}
LinearLayout container = new LinearLayout(getContext());
container.setLayoutParams(mFrameParams);
container.setOrientation(LinearLayout.VERTICAL);
return container;
}
private void setVisibility(LinearLayout container) {
int count = container.getChildCount();
for (int i = 0; i < count; i++) {
container.getChildAt(i).setVisibility(VISIBLE);
}
}
private TextView createTextView(String text) {
if (mLinearParams == null) {
mLinearParams = new LinearLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
mLinearParams.gravity = Gravity.CENTER_VERTICAL;
}
TextView textView = new TextView(getContext());
textView.setLayoutParams(mLinearParams);
textView.setSingleLine();
textView.setPadding(mTextPadding, mTextPadding, mTextPadding, mTextPadding);
textView.setEllipsize(TextUtils.TruncateAt.END);
textView.setTextColor(mTextColor);
textView.setVisibility(INVISIBLE);
textView.setText(text);
if (mLeftDrawable > 0) {
Drawable drawable = getContext().getResources().getDrawable(mLeftDrawable);
drawable.setBounds(0, 0, 10, 10);
textView.setCompoundDrawablePadding(10);
textView.setCompoundDrawables(drawable, null, null, null);
}
textView.setOnClickListener(this);
if (mTextSize > 0) {
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
}
return textView;
}
private void createEnterAnimation() {
mEnterAnimSet = new AnimationSet(false);
TranslateAnimation translate = new TranslateAnimation(
0, 0, 0, 0,
TranslateAnimation.RELATIVE_TO_PARENT, 1f,
TranslateAnimation.RELATIVE_TO_SELF, 0f);
AlphaAnimation alpha = new AlphaAnimation(0f, 1f);
mEnterAnimSet.addAnimation(translate);
mEnterAnimSet.addAnimation(alpha);
mEnterAnimSet.setDuration(ANIMATION_DURATION);
}
private void createExitAnimation() {
mExitAnimSet = new AnimationSet(false);
TranslateAnimation translate = new TranslateAnimation(
0, 0, 0, 0,
TranslateAnimation.RELATIVE_TO_SELF, 0f,
TranslateAnimation.RELATIVE_TO_PARENT, -1f);
AlphaAnimation alpha = new AlphaAnimation(1f, 0f);
mExitAnimSet.addAnimation(translate);
mExitAnimSet.addAnimation(alpha);
mExitAnimSet.setDuration(ANIMATION_DURATION);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
pause();
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
resume();
break;
}
return true;
}
public void resume() {
if (mPageCount < 1) return;
if (mRunnable == null) {
mRunnable = new RollingRunnable();
} else {
mHandler.removeCallbacks(mRunnable);
}
mHandler.postDelayed(mRunnable, mDuration);
}
public void pause() {
if (mRunnable != null) {
mHandler.removeCallbacks(mRunnable);
}
}
@Override
public void onClick(View v) {
if (null == mClickListener) return;
TextView textView = (TextView) v;
mClickListener.onItemClick(textView);
textView.setTextColor(mClickColor);
}
/** 隱藏當前頁並顯示下一頁 */
public class RollingRunnable implements Runnable {
@Override
public void run() {
LinearLayout currentView = mRollingPages.get(mCurrentPage);
currentView.setVisibility(INVISIBLE);
if (mExitAnimSet != null) {
currentView.startAnimation(mExitAnimSet);
}
mCurrentPage++;
if (mCurrentPage >= mPageCount) {
mCurrentPage = 0;
}
LinearLayout nextView = mRollingPages.get(mCurrentPage);
nextView.setVisibility(VISIBLE);
setVisibility(nextView);
if (mEnterAnimSet != null) {
nextView.startAnimation(mEnterAnimSet);
}
mHandler.postDelayed(this, mDuration);
}
}
/** 3D 翻轉動畫 */
public class Rotate3dAnimation extends Animation {
private final float mFromDegrees;
private final float mToDegrees;
private final boolean mTurnIn;
private final boolean mTurnUp;
private float mCenterX;
private float mCenterY;
private Camera mCamera;
public Rotate3dAnimation(float fromDegrees, float toDegrees,
boolean turnIn, boolean turnUp) {
mFromDegrees = fromDegrees;
mToDegrees = toDegrees;
mTurnIn = turnIn;
mTurnUp = turnUp;
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
mCamera = new Camera();
mCenterY = getHeight() / 2;
mCenterX = getWidth() / 2;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float degrees = mFromDegrees + ((mToDegrees - mFromDegrees) * interpolatedTime);
final float centerX = mCenterX;
final float centerY = mCenterY;
final Camera camera = mCamera;
final int direction = mTurnUp ? 1 : -1;
final Matrix matrix = t.getMatrix();
camera.save();
if (mTurnIn) {
camera.translate(0.0f, direction * mCenterY * (interpolatedTime - 1.0f), 0.0f);
} else {
camera.translate(0.0f, direction * mCenterY * interpolatedTime, 0.0f);
}
camera.rotateX(degrees);
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
}
}
public interface onItemClickListener {
void onItemClick(TextView v);
}
}
// 準備資料
List<String> haowaiArray = new ArrayList<>();
haowaiArray.add("[母嬰天地] 買尿不濕送嬰兒手口濕巾");
haowaiArray.add("[利民商店] 滿100免費配送");
haowaiArray.add("[果之家] 泰國金枕榴蓮8元/kg");
haowaiArray.add("[戶外運動] 戶外運動專業裝備搜集");
haowaiArray.add("[天天特價] 只要9.9還包郵");
haowaiArray.add("[尖端潮品] 折疊電動車");
haowaiArray.add("[黑科技] 智能VR帶你裝13");
haowaiArray.add("[旅行必備] 太陽能充電寶-永不斷電");
// 綁定資料
mRollingView.setPageSize(4);
mRollingView.setClickColor(0xff888888);
mRollingView.setLeftDrawable(R.drawable.drawable_red_dot);
mRollingView.setRollingText(haowaiArray);
mRollingView.setOnItemClickListener(this);
@Override
public void onItemClick(TextView v) {
// 處理點擊事件
}
@Override
public void onResume() {
super.onResume();
mRollingView.resume();
}
@Override
public void onPause() {
super.onPause();
mRollingView.pause();
}
<declare-styleable name="RollingView">
<attr name="textSize" format="dimension" />
<attr name="textColor" format="reference|color" />
</declare-styleable>
分頁策略。 setRollingText 先用商與餘數算出總頁數,再逐頁建立 LinearLayout 容器,每頁裝 mPageSize 個 TextView。最後一頁若不足則用餘數收尾,避免索引越界。
動畫替換。 元件同時準備了兩套動畫:預設的「平移 + 淡入淡出」AnimationSet,以及四個 Rotate3dAnimation(進場上翻、退場上翻、進場下翻、退場下翻)。建構時預設使用前者,但你可以透過 setEnterAnimation / setExitAnimation 換成 3D 版本,RollingRunnable 裡也留了註解提示替換位置。
3D 效果的關鍵。 Camera 提供虛擬的透視空間,rotateX 讓畫面繞水平軸翻轉,translate 依進場/退場給出不同的 Z 軸位移,最後用 pre / postTranslate 把旋轉中心校正回檢視中央。少了最後這步校正,畫面會繞著左上角翻,看起來非常怪。
生命週期必須配對。 這個元件在 onResume 啟動定時器、onPause 取消,務必成對呼叫。否則 Activity 退到背景後 Handler 仍在 postDelayed,不僅浪費資源,也可能在 View 已銷毀後嘗試操作它。
Android Service 完全解析:兩種啟動方式與生命週期實戰
Service 存在的意義是什麼 很多初學者會疑惑:Service 究竟用來做什麼?作為 Android 四大組件之一,你可以把它理解成「沒有界面的 Activity」—
Android 系列:JSON 資料解析實戰(json-lib 與 Gson)
上一篇詳細介紹了如何解析伺服器端回傳的 XML 資料。而伺服器與客戶端之間的資料交換格式,實務上以 HTML、XML 和 JSON 三種最為常見。本篇聚焦 JSON,內容
微信小程序 Banner 輪播實作:全螢幕切換與索引同步
輪播圖基本設定 微信小程序的 Banner 輪播通常使用 swiper 元件完成。autoplay 控制是否自動播放,interval 設定每頁停留時間,duration
Android 系統服務 SmsManager 短信管理器用法
在 Android 開發中,SmsManager 是系統提供的短信管理服務,主要用於在應用內完成短信內容編排與發送。常見做法有兩種:一種是調起系統短信介面,由使用者確認後