編輯:關於 Android 程式設計
又有兩週沒寫 Blog 了。不是不想寫,是真的不知道寫什麼,總不能為了更新而更新。前幾天專案裡要加購物車,試看了幾家 App 的效果覺得做得不錯,雖然這次自己沒用上,但畢竟算高頻功能,就整理成一篇分享出來。

畫面看起來熱鬧,實際需要處理的東西並不多,值得一談的主要是這幾塊:
· 列表標題懸停
· 左右兩欄滑動聯動
· 加入商品時的拋物線動畫
· 底部彈出的購物車清單
· 多處視圖之間的資料同步
除此之外,還有幾個實作過程中真的踩到的坑,後面會一併說明。
現在做列表我基本不用 ListView 了,改投 RecyclerView。上一篇 Blog 的懸停效果用的是開源專案 sticky-headers-recyclerview,但這次實作遇到兩個問題:
1. scrollToPosition(int position) 捲動到的位置不準。
2. 當版面結構複雜一些,例如 RecyclerView 寬度自適應或用權重百分比時,header 可能顯示成空白。
加上該專案作者已經停止維護,所以這次換回 StickyListHeadersListView。
考虑到想看這篇 Demo 的不少人還是新手,這裡簡單說明用法。
先在 gradle 的 dependencies 中加入:
compile 'se.emilsjolander:stickylistheaders:2.7.0'
版面中用 StickyListHeadersListView 取代原本的 ListView:
<se.emilsjolander.stickylistheaders.stickylistheaderslistview
android:id="@+id/itemListView"
android:background="#fff"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Adapter 除了繼承 BaseAdapter,還要實作 StickyListHeadersAdapter 介面,它要求兩個方法:
View getHeaderView(int position, View convertView, ViewGroup parent); long getHeaderId(int position);
其餘用法與 ListView 幾乎一致,另外多了幾個專屬方法,看名字就懂:
public void setAreHeadersSticky(boolean areHeadersSticky); public boolean areHeadersSticky(); public void setOnHeaderClickListener(OnHeaderClickListener listener); public void setOnStickyHeaderChangedListener(OnStickyHeaderChangedListener listener); public View getListChildAt(int index); public int getListChildCount();
聯動要做的是兩件事:
· 左欄點分類,右欄捲到對應位置
· 右欄滑動時,左欄的高亮分類跟著變
第一件事很簡單:左欄 item 掛點擊事件,回呼右欄的 setSelection(int position)。
第二件事則要幫右欄掛 OnScrollListener,依「畫面上第一筆資料」反推左欄該選中哪一項:
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override public void onScrollStateChanged(AbsListView view, int scrollState) { }
@Override public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
GoodsItem item = dataList.get(firstVisibleItem);
if (typeAdapter.selectTypeId != item.typeId) {
typeAdapter.selectTypeId = item.typeId;
typeAdapter.notifyDataSetChanged();
// 左欄是 RecyclerView,用 smoothScrollToPosition 讓項目捲進視線
rvType.smoothScrollToPosition(getSelectedGroupPosition(item.typeId));
}
}
});
加號互動其實包含三段動畫:
· 商品從 0 到 1:旋轉左移,減號按鈕浮現
· 商品從 1 到 0:減號按鈕旋轉右移後消失
· 點擊瞬間:商品沿拋物線飛向購物車圖示
前兩段可以拆成旋轉、平移、透明度三個補間動畫組合,寫在 XML 或純程式碼都行。這裡有個坑:旋轉動畫一定要排在平移動畫之前,順序顛倒的話就不是「滾著平移」,而是四處亂跳。
// 顯示減號
private Animation getShowAnimation() {
AnimationSet set = new AnimationSet(true);
set.addAnimation(new RotateAnimation(0, 720,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f));
set.addAnimation(new TranslateAnimation(
TranslateAnimation.RELATIVE_TO_SELF, 2f,
TranslateAnimation.RELATIVE_TO_SELF, 0,
TranslateAnimation.RELATIVE_TO_SELF, 0,
TranslateAnimation.RELATIVE_TO_SELF, 0));
set.addAnimation(new AlphaAnimation(0, 1));
set.setDuration(500);
return set;
}
// 隱藏減號
private Animation getHiddenAnimation() {
AnimationSet set = new AnimationSet(true);
set.addAnimation(new RotateAnimation(0, 720,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f));
set.addAnimation(new TranslateAnimation(
TranslateAnimation.RELATIVE_TO_SELF, 0,
TranslateAnimation.RELATIVE_TO_SELF, 2f,
TranslateAnimation.RELATIVE_TO_SELF, 0,
TranslateAnimation.RELATIVE_TO_SELF, 0));
set.addAnimation(new AlphaAnimation(1, 0));
set.setDuration(500);
return set;
}
// 執行:先 setAnimation,再切可見性
tvMinus.setAnimation(getHiddenAnimation());
tvMinus.setVisibility(View.GONE);
拋物線動畫的原理類似,只是拆成水平與垂直兩段平移,兩者插值器不同——水平線性、垂直加速,合起來就是抛物線的手感。
這裡有個容易忽略的細節:動畫跨度大,所以必須掛在整個版面的根佈局上,寫在列表 item 裡會顯示不全。程式碼中的 anim_mask_layout 就是根佈局,本例是 RelativeLayout。
實作步驟如下。第一步,點擊時取得控件在視窗中的絕對座標,回呼 Activity 播放動畫:
int[] loc = new int[2]; v.getLocationInWindow(loc); activity.playAnimation(loc);
第二步,建立動畫用的 ImageView、掛到根佈局,動畫結束後再移除:
public void playAnimation(int[] start_location) {
ImageView img = new ImageView(this);
img.setImageResource(R.drawable.button_add);
setAnim(img, start_location);
}
private Animation createAnim(int startX, int startY) {
int[] des = new int[2];
imgCart.getLocationInWindow(des);
AnimationSet set = new AnimationSet(false);
Animation translationX = new TranslateAnimation(0, des[0] - startX, 0, 0);
translationX.setInterpolator(new LinearInterpolator()); // 水平:線性
Animation translationY = new TranslateAnimation(0, 0, 0, des[1] - startY);
translationY.setInterpolator(new AccelerateInterpolator()); // 垂直:加速
Animation alpha = new AlphaAnimation(1, 0.5f);
set.addAnimation(translationX);
set.addAnimation(translationY);
set.addAnimation(alpha);
set.setDuration(500);
return set;
}
private void addViewToAnimLayout(final ViewGroup vg, final View view, int[] location) {
int[] loc = new int[2];
vg.getLocationInWindow(loc);
view.setX(location[0]);
view.setY(location[1] - loc[1]); // 換算成根佈局內的相對座標
vg.addView(view);
}
private void setAnim(final View v, int[] start_location) {
addViewToAnimLayout(anim_mask_layout, v, start_location);
Animation set = createAnim(start_location[0], start_location[1]);
set.setAnimationListener(new Animation.AnimationListener() {
@Override public void onAnimationStart(Animation animation) { }
@Override public void onAnimationEnd(final Animation animation) {
// 直接 remove 可能因為畫面仍在繪製而報錯,延一點再移除
mHanlder.postDelayed(new Runnable() {
@Override public void run() { anim_mask_layout.removeView(v); }
}, 100);
}
@Override public void onAnimationRepeat(Animation animation) { }
});
v.startAnimation(set);
}
從底部彈出的效果幾乎每個專案都會用到,官方沒有現成控件,自己寫又要兼顧流暢與可移植性,因此我偏好用現成的庫。這裡推薦 bottomsheet:接入簡單、效果多樣。
compile 'com.flipboard:bottomsheet-core:1.5.1'
它的 BottomSheetLayout 繼承自 FrameLayout,用來包住「要彈出時被覆蓋的背景版面」:
<com.flipboard.bottomsheet.bottomsheetlayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/bottomSheetLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<se.emilsjolander.stickylistheaders.stickylistheaderslistview
android:id="@+id/itemListView"
android:background="#fff"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</com.flipboard.bottomsheet.bottomsheetlayout>
程式碼側只要兩行:
bottomSheetLayout.showWithSheetView(bottomSheet); // 彈出 bottomSheetLayout.dismissSheet(); // 收起
點擊彈出層以外的地方、或往下滑動,都能自動收起,這些細節庫已經幫你處理好了。
多處視圖共用一份資料,該怎麼管?這大概是新手最容易繞遠路的地方。這裡提供一種思路,不一定適合所有專案,但足夠清晰。
private ArrayList<GoodsItem> dataList; // 商品列表 private ArrayList<GoodsItem> typeList; // 分類列表 private SparseArray<GoodsItem> selectedList; // 已選商品,key 為商品 id private SparseIntArray groupSelect; // 各分組的已選數量
SparseArray 你可以理解成 HashMap<Integer, Object> 的替代品,但它同時支援依 key 和依索引取值,記憶體開銷更小,是官方推薦的做法;SparseIntArray 同理,對應 HashMap<Integer, Integer>。
接著把「加」「減」「查」統一收到 Activity,讓所有界面都從同一處取數:
/** 某項商品 +1 */
public void add(GoodsItem item, boolean refreshGoodList) {
int groupCount = groupSelect.get(item.typeId);
groupSelect.append(item.typeId, groupCount == 0 ? 1 : ++groupCount);
GoodsItem temp = selectedList.get(item.id);
if (temp == null) {
item.count = 1;
selectedList.append(item.id, item);
} else {
temp.count++;
}
update(refreshGoodList);
}
/** 某項商品 -1 */
public void remove(GoodsItem item, boolean refreshGoodList) {
int groupCount = groupSelect.get(item.typeId);
if (groupCount == 1) {
groupSelect.delete(item.typeId);
} else if (groupCount > 1) {
groupSelect.append(item.typeId, --groupCount);
}
GoodsItem temp = selectedList.get(item.id);
if (temp != null) {
if (temp.count < 2) {
selectedList.remove(item.id);
} else {
item.count--;
}
}
update(refreshGoodList);
}
/** 刷新總價、總數量等 */
private void update(boolean refreshGoodList) { ... }
/** 依商品 id 取得採購數量 */
public int getSelectedItemCountById(int id) {
GoodsItem temp = selectedList.get(id);
return temp == null ? 0 : temp.count;
}
/** 依分類 id 取得該類的總數量 */
public int getSelectedGroupCountByTypeId(int typeId) {
return groupSelect.get(typeId);
}
這套寫法的關鍵在於:列表裡顯示的數量一律回 Activity 拿,加減動作一律呼叫 Activity 的方法,然後由 Activity 決定要不要 notifyDataSetChanged。資料只有一個來源,介面自然不會對不上。剩下的細節就留給原始碼吧。
利用 android-wheel 控件實現省、市、縣三級聯動
本文為大家分享一個基於開源控件 Android-wheel 實現省、市、縣三級聯動的完整示例,供大家參考。 GitHub 上有一個名為 Android-wheel 的開源
自定義 View 的兩個隱形陷阱:merge 標籤與構造函數
在 Android 裡自定義 View,本質上不複雜:繼承合適的父類,重載需要的方法。即便如此,實際編碼時還是容易踩坑。本文總結兩個我親身遇到過的問題,希望能幫你少走彎路
Android 透過 startService 播放背景音樂簡單範例
關於 startService 的基本用法與生命週期,可參考〈Android 中 startService 的使用及 Service 生命週期〉一文。本文則透過播放背景音
動手打造Android下拉刷新與上拉加載更多的自定義ListView
下拉刷新、上拉加載更多的擴展ListView 我們幾乎可以在每一款App裡看到這樣的互動:手指在列表上往下一拉,列表頂部就露出一塊隱藏的視圖,上面寫著「下拉刷新」;繼續下