編輯:關於 Android 程式設計
新版 360 手機助手的底部導航做得很精緻,切換 Tab 時那層從中央蕩開的波紋動畫尤其討喜。前陣子翻到一個開源專案,才發現用 Drawable 做動畫居然這麼順手,於是照著思路自己實現了一個帶波紋效果的 TabHost。源碼地址:https://github.com/Rukey7/XFragmentTabHost
先看效果:

實現要點只有三條:
FragmentTabHost,直接繼承它來擴充最省事。自定義 Drawable 只需繼承 Drawable 並實作四個方法,同時實作 Animatable 介面。
public class RippleDrawable extends Drawable implements Animatable {
@Override public void draw(Canvas canvas) { /* 繪圖,核心 */ }
@Override public void setAlpha(int alpha) {}
@Override public void setColorFilter(ColorFilter colorFilter) {}
@Override public int getOpacity() { return PixelFormat.RGBA_8888; }
@Override public void start() { /* 啟動動畫 */ }
@Override public void stop() { /* 停止動畫 */ }
@Override public boolean isRunning() { return false; }
}
其中 draw() 是重點,所有圖形都在這裡畫出來;getOpacity() 用來宣告 Drawable 的顏色格式;後三個方法來自 Animatable,負責控制動畫生命週期。老實說不實作這個介面也能做出動畫,但既然要規範一點,還是實作比較好。
完整的波紋 Drawable:
public class RippleDrawable extends Drawable implements Animatable {
public static final int MODE_LEFT = 1;
public static final int MODE_MIDDLE = 2;
public static final int MODE_RIGHT = 3;
private int mMode = MODE_MIDDLE;
private Paint mPaintFront; // 前景色畫筆
private Paint mPaintBehind; // 後景色畫筆
private RectF mRect; // 繪製扇形的矩形框
private int mHalfWidth; // 目標 View 寬度的一半
private int mHalfHeight; // 目標 View 高度的一半
private int mRadius; // 當前擴散半徑
private int mDivideSpace; // 前景與背景的分割距離
private int mFullSpace; // 鋪滿整個視圖所需的半徑(中心到斜角)
private ValueAnimator mValueAnimator;
public RippleDrawable(int frontColor, int behindColor, int mode) {
mPaintFront = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintFront.setColor(frontColor);
mPaintBehind = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintBehind.setColor(behindColor);
mRect = new RectF();
mMode = mode;
}
@Override
public void draw(Canvas canvas) {
if (mRadius > mHalfWidth) {
int count = canvas.save();
canvas.drawCircle(mHalfWidth, mHalfHeight, mHalfWidth, mPaintBehind);
canvas.restoreToCount(count);
count = canvas.save();
canvas.drawCircle(mHalfWidth, mHalfHeight, mDivideSpace, mPaintFront);
canvas.restoreToCount(count);
} else if (mRadius > mDivideSpace) {
int count = canvas.save();
canvas.drawCircle(mHalfWidth, mHalfHeight, mRadius, mPaintBehind);
canvas.restoreToCount(count);
count = canvas.save();
canvas.drawCircle(mHalfWidth, mHalfHeight, mDivideSpace, mPaintFront);
canvas.restoreToCount(count);
} else {
canvas.drawCircle(mHalfWidth, mHalfHeight, mRadius, mPaintFront);
}
// 左右兩端才需要補扇形,填滿 Tab 的邊角
if (mMode != MODE_MIDDLE) {
mRect.left = mHalfWidth - mRadius;
mRect.right = mHalfWidth + mRadius;
mRect.top = mHalfHeight - mRadius;
mRect.bottom = mHalfHeight + mRadius;
}
if (mMode == MODE_LEFT) {
canvas.drawArc(mRect, 90, 180, true, mPaintFront);
} else if (mMode == MODE_RIGHT) {
canvas.drawArc(mRect, -90, 180, true, mPaintFront);
}
}
@Override public void setAlpha(int alpha) {}
@Override public void setColorFilter(ColorFilter colorFilter) {}
@Override public int getOpacity() { return PixelFormat.RGBA_8888; }
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mHalfHeight = (bounds.bottom - bounds.top) / 2;
mHalfWidth = (bounds.right - bounds.left) / 2;
mDivideSpace = Math.max(mHalfHeight, mHalfWidth) * 3 / 4;
mFullSpace = (int) Math.sqrt(mHalfWidth * mHalfWidth + mHalfHeight * mHalfHeight);
mValueAnimator = ValueAnimator.ofInt(0, mFullSpace);
mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mRadius = (int) animation.getAnimatedValue();
invalidateSelf(); // 觸發重繪
}
});
mValueAnimator.setDuration(200);
start();
}
@Override public void start() { mValueAnimator.start(); }
@Override public void stop() { mValueAnimator.end(); }
@Override public boolean isRunning() {
return mValueAnimator != null && mValueAnimator.isRunning();
}
}
代碼不長,核心就在繪圖部分。draw() 一共要畫三個圖形:一個前景色圓、一個後景色圓,以及左右兩端用來填角的扇形,三者的圓心都是 Tab 項的中心。繪製前得先把半徑算清楚。onBoundsChange() 是拿到 Tab 項尺寸的地方:mDivideSpace 是前景色圓的半徑,也就是前景與背景的分割線;後景色圓的半徑取 Tab 項寬度的一半;mFullSpace 則是中心到 Tab 斜角的距離,用來保證波紋最終能鋪滿整個矩形。
動畫部分靠一個 ValueAnimator 驅動 mRadius 從 0 增長到 mFullSpace。這裡有個容易踩的點:Drawable 不能像 View 那樣調 invalidate(),必須調 invalidateSelf() 才會重新觸發 draw(),波紋 therefore 才能一圈圈蕩開。
要接入動畫,關鍵是覆寫 setCurrentTab(int index)。FragmentTabHost 在切換 Tab 時會呼叫這個方法,在這裡我們既能拿到新選中的索引,也能透過 getCurrentTab() 拿到上一個索引,剛好足夠做過渡處理。
Tab 項的佈局很樸素,就是圖標加標題:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="@dimen/tab_height"
android:minWidth="@dimen/tab_min_width"
android:orientation="vertical"
android:paddingTop="@dimen/tab_padding_top_inactive"
android:paddingBottom="@dimen/tab_padding_bottom"
android:background="?selectableItemBackgroundBorderless">
<ImageView
android:id="@+id/tab_icon"
android:layout_width="@dimen/tab_icon"
android:layout_height="@dimen/tab_icon"
android:layout_gravity="center_horizontal" />
<TextView
android:id="@+id/tab_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:lines="1"
android:textColor="@color/colorInactive"
android:textSize="@dimen/tab_text_size_inactive" />
</LinearLayout>
與佈局對應的數據模型:
public class TabItem {
private String title;
private int imageRes;
public TabItem(String title, int imageRes) {
this.title = title;
this.imageRes = imageRes;
}
// getter / setter 省略
}
擴展後的 TabHost:
public class XFragmentTabHost extends FragmentTabHost {
private Context mContext;
private List<View> mTabViews;
private List<TabItem> mTabItems;
private int mTextActiveColor;
private int mTextInactiveColor;
private float mTextActiveSize;
private float mTextInactiveSize;
private int mViewActivePaddingTop;
private int mViewInactivePaddingTop;
private int mFrontColor;
private int mBehindColor;
public XFragmentTabHost(Context context) {
super(context);
_init(context);
}
public XFragmentTabHost(Context context, AttributeSet attrs) {
super(context, attrs);
_init(context);
}
private void _init(Context context) {
mTabViews = new ArrayList<>();
mTabItems = new ArrayList<>();
mContext = context;
mTextActiveColor = ContextCompat.getColor(mContext, R.color.colorActive);
mTextInactiveColor = ContextCompat.getColor(mContext, R.color.colorInactive);
mFrontColor = ContextCompat.getColor(mContext, R.color.colorFront);
mBehindColor = ContextCompat.getColor(mContext, R.color.colorBehind);
mTextActiveSize = getResources().getDimension(R.dimen.tab_text_size_active);
mTextInactiveSize = getResources().getDimension(R.dimen.tab_text_size_inactive);
mViewActivePaddingTop = (int) getResources().getDimension(R.dimen.tab_padding_top_active);
mViewInactivePaddingTop = (int) getResources().getDimension(R.dimen.tab_padding_top_inactive);
}
/** 覆寫父類方法,在這裡插入動畫處理 */
@Override
public void setCurrentTab(int index) {
int lastIndex = getCurrentTab();
super.setCurrentTab(index);
if (lastIndex != index) {
_switchTab(lastIndex, index);
}
}
public void addTabItem(TabItem item, Class<?> fragClass, Bundle bundle) {
mTabItems.add(item);
View view = _getIndicator(item);
mTabViews.add(view);
this.addTab(newTabSpec(item.getTitle()).setIndicator(view), fragClass, bundle);
}
private View _getIndicator(TabItem item) {
View view = LayoutInflater.from(mContext).inflate(R.layout.tab_indicator, null);
ImageView imageView = view.findViewById(R.id.tab_icon);
TextView title = view.findViewById(R.id.tab_title);
imageView.setImageResource(item.getImageRes());
title.setText(item.getTitle());
title.setTextColor(mTextInactiveColor);
return view;
}
private void _switchTab(int lastIndex, int nextIndex) {
for (int i = 0; i < mTabViews.size(); i++) {
if (i == lastIndex) {
_doRipple(i, false);
} else if (i == nextIndex) {
_doRipple(i, true);
}
}
}
private void _doRipple(int index, boolean isActivated) {
View view = mTabViews.get(index);
View tabView = view.findViewById(R.id.tab_layout);
TextView title = view.findViewById(R.id.tab_title);
if (index == 0) {
_rippleDrawable(tabView, mFrontColor, mBehindColor, RippleDrawable.MODE_LEFT, isActivated);
} else if (index == mTabViews.size() - 1) {
_rippleDrawable(tabView, mFrontColor, mBehindColor, RippleDrawable.MODE_RIGHT, isActivated);
} else {
_rippleDrawable(tabView, mFrontColor, mBehindColor, RippleDrawable.MODE_MIDDLE, isActivated);
}
title.setTextColor(isActivated ? mTextActiveColor : mTextInactiveColor);
}
@SuppressWarnings("deprecation")
private void _rippleDrawable(final View view, int frontColor, int behindColor,
int mode, boolean isActivated) {
if (isActivated) {
RippleDrawable rippleDrawable = new RippleDrawable(frontColor, behindColor, mode);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(rippleDrawable);
} else {
view.setBackgroundDrawable(rippleDrawable);
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.setBackground(null);
} else {
view.setBackgroundDrawable(null);
}
}
}
// 各項屬性 getter / setter 省略
}
邏輯說穿了很簡單:切換 Tab 時,給新選中的項掛上 RippleDrawable 作為背景,把舊項的背景清成 null,動畫就自己跑起來了。使用方式和原生 FragmentTabHost 幾乎一致,只要把 addTab() 換成 addTabItem(item, fragClass, bundle)。
順帶一提,最左和最右兩個 Tab 之所以要區分 MODE_LEFT / MODE_RIGHT,是因為圓形擴散會溢出 Tab 項邊界,需要補上扇形才能讓波紋貼齊邊角、視覺上不出現缺口。
這個 TabHost 實現難度並不高,核心就是替 Drawable 寫個半徑遞增的動畫。源碼裡還有其他幾種切換動畫,思路完全相通,有興趣可以自己改出更好看的變化。
Android 以 PopupWindow 實作滑動刪除(精簡版)
本文參考〈Android 仿騰訊 QQ 實現滑動刪除〉一文進行學習。該文實作的功能是:在 ListView 的 Item 上從右向左滑動時出現刪除按鈕,點擊刪除按鈕即可刪
Android 屏幕適配完全攻略
一、為什麼需要做屏幕適配 由於 Android 系統的開放性,用戶、開發者、OEM 廠商乃至運營商都可以對它進行定制,改成各自想要的樣子。那麼這種「碎片化」究竟嚴重到什麼
iOS 開發:UIPickerView 滾動選擇器實作教學
UIPickerView 的功能與 UIDatePicker 相似,但更為靈活。初始化時通常只需設定原點座標,無須指定寬高(預設大小為 frame = (0 0; 320
ListView 異步載入與圖片緩存實踐
需求說明 本範例示範如何從網路異步取得文字與圖片資料,並顯示在 ListView 中。同時,透過記憶體緩存保存已下載的圖片,避免重複請求,提升列表滾動的流暢度。 佈局