編輯:關於 Android 程式設計
本文拆解一個外賣風格購物車的完整實作,重點放在幾個能直接搬到專案裡的技巧,以及實作過程中容易踩到的坑。

畫面看起來熱鬧,真正需要處理的核心其實就這幾項:
· 列表標題懸浮
· 左右兩欄滑動聯動
· 加入商品時的拋物線動畫
· 底部彈出的購物車清單
· 各處資料的同步
近來做列表已大致從 ListView 換到 RecyclerView。標題懸浮一開始用的是開源專案 sticky-headers-recyclerview,但實作時遇到兩個問題:
1、scrollToPosition(int position) 捲動的位置不夠精準。
2、版面一複雜,若 RecyclerView 寬度採用自適應或權重百分比,header 可能出現空白。
加上該專案作者已停止維護,因此改回 StickyListHeadersListView。
// build.gradle 的 dependencies 區塊加入 compile 'se.emilsjolander:stickylistheaders:2.7.0'
<se.emilsjolander.stickylistheaders.StickyListHeadersListView
android:layout_width="match_parent"
android:background="#fff"
android:id="@+id/itemListView"
android:layout_height="match_parent">
</se.emilsjolander.stickylistheaders.StickyListHeadersListView>
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) 即可。
第二個需要替右欄掛上 ScrollListener,依目前顯示的第一筆資料決定左欄該高亮哪一項:
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) {
// 依 firstVisibleItem 找到分類 ID,再換算左欄要選中的位置
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);
RotateAnimation rotate = new RotateAnimation(0, 720,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
set.addAnimation(rotate);
TranslateAnimation translate = new TranslateAnimation(
TranslateAnimation.RELATIVE_TO_SELF, 2f,
TranslateAnimation.RELATIVE_TO_SELF, 0,
TranslateAnimation.RELATIVE_TO_SELF, 0,
TranslateAnimation.RELATIVE_TO_SELF, 0);
set.addAnimation(translate);
AlphaAnimation alpha = new AlphaAnimation(0, 1);
set.addAnimation(alpha);
set.setDuration(500);
return set;
}
// 隱藏減號
private Animation getHiddenAnimation() {
AnimationSet set = new AnimationSet(true);
RotateAnimation rotate = new RotateAnimation(0, 720,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
set.addAnimation(rotate);
TranslateAnimation translate = new TranslateAnimation(
TranslateAnimation.RELATIVE_TO_SELF, 0,
TranslateAnimation.RELATIVE_TO_SELF, 2f,
TranslateAnimation.RELATIVE_TO_SELF, 0,
TranslateAnimation.RELATIVE_TO_SELF, 0);
set.addAnimation(translate);
AlphaAnimation alpha = new AlphaAnimation(1, 0);
set.addAnimation(alpha);
set.setDuration(500);
return set;
}
// 套用動畫並同步切換可見性
tvMinus.setAnimation(getHiddenAnimation());
tvMinus.setVisibility(View.GONE);
拋物線可以拆成 X、Y 兩段平移動畫,差別只在插值器:X 用線性、Y 用加速,合起來就是自然的拋物線。因為動畫跨度橫掃整個畫面,必須掛在根版面上(本例的 anim_mask_layout 是一個 RelativeLayout),寫在列表 item 裡會被裁切顯示不全。
// 1. 點擊加號時取得控件在視窗中的絕對座標,交由 Activity 播放動畫
int[] loc = new int[2];
v.getLocationInWindow(loc);
activity.playAnimation(loc);
// 2. 建立動畫用的 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;
}
// 換算動畫 View 在根版面中的座標並加入
private void addViewToAnimLayout(final ViewGroup vg, final View view, int[] location) {
int x = location[0];
int y = location[1];
int[] loc = new int[2];
vg.getLocationInWindow(loc);
view.setX(x);
view.setY(y - loc[1]);
vg.addView(view);
}
// 動畫結束後移除,避免繪製過程中直接 remove 造成錯誤
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) {
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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="100dp"
android:id="@+id/typeRecyclerView"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
<se.emilsjolander.stickylistheaders.StickyListHeadersListView
android:layout_width="match_parent"
android:background="#fff"
android:id="@+id/itemListView"
android:layout_height="match_parent">
</se.emilsjolander.stickylistheaders.StickyListHeadersListView>
</LinearLayout>
</com.flipboard.bottomsheet.BottomSheetLayout>
// 彈出:傳入要顯示的 View bottomSheetLayout.showWithSheetView(bottomSheet); // 收起:點擊彈出層以外的地方或向下滑動也會自動收起 bottomSheetLayout.dismissSheet();
資料同步與畫面刷新,是新手最容易繞遠路的地方。這裡提供一種思路,並不一定最適合你的專案,但足夠清晰:
// 商品列表 private ArrayList<GoodsItem> dataList; // 分類列表 private ArrayList<GoodsItem> typeList; // 已選取的商品 private SparseArray<GoodsItem> selectedList; // 記錄每個分組已選的數量 private SparseIntArray groupSelect;
SparseArray 基本上就是 HashMap<Integer, Object>,但它既能用 key 查找也能用 index 定位,效能優於 HashMap,是官方推薦的替代類;SparseIntArray 則對應 HashMap<Integer, Integer>。
接著把資料操作全部集中在 Activity,讓商品數量只有一個真相來源:列表顯示的數量一律向 Activity 索取,加減一律呼叫 Activity 的方法,再由它統一 notifyDataSetChanged。
/**
* 商品購買數量 +1
* @param refreshGoodList 是否同時刷新商品列表
*/
public void add(GoodsItem item, boolean refreshGoodList) {
int groupCount = groupSelect.get(item.typeId);
if (groupCount == 0) {
groupSelect.append(item.typeId, 1);
} else {
groupSelect.append(item.typeId, ++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);
if (temp == null) {
return 0;
}
return temp.count;
}
/** 依分類 id 取得該分類的已選數量 */
public int getSelectedGroupCountByTypeId(int typeId) {
return groupSelect.get(typeId);
}
整體邏輯就是這樣:所有狀態由 Activity 統一持有,View 只負責呼叫與呈現,雙向聯動與資料一致性自然就成立了。
Android OTTO 事件總線實戰:以短信接收為例
OTTO 是一個 EventBus 類型的事件傳輸總線,提供「儲存轉發」能力,讓 App 內各個組件之間的溝通更便利,分層也更清晰。 適用場景 OTTO 基於 Obser
Android 開發:APK 反編譯與防止反編譯(代碼混淆)
防止反編譯是每个開發者的必修課。辛辛苦苦做出來的應用,被別人三兩下反編譯並改頭換面,是件尷尬又洩氣的事。那麼該怎麼防?這裡用 Google Android 自帶的代碼混淆
Android 自訂 ActionBar 實作教學
本文以實例說明如何打造一個自訂的 ActionBar,供大家參考。 Android 3.0 以上已內建 ActionBar API,也能透過引入 support pack
Android 安全透視:ContentProvider 如何讀取短信與舊版系統的短信寫入風險
相比於 iOS,Android 系統一直為人詬病的一點就是安全性。本篇就從開發者與安全研究的角度,剖析短信數據庫的存取機制,藉此理解為什麼要謹慎授予應用敏感權限。 一、應