Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 傚外賣 App 購物車實作:懸浮標題、左右聯動與拋物線動畫

編輯:關於 Android 程式設計

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

先盤點技術點

畫面看起來熱鬧,真正需要處理的核心其實就這幾項:

· 列表標題懸浮
· 左右兩欄滑動聯動
· 加入商品時的拋物線動畫
· 底部彈出的購物車清單
· 各處資料的同步

一、列表標題懸浮

近來做列表已大致從 ListView 換到 RecyclerView。標題懸浮一開始用的是開源專案 sticky-headers-recyclerview,但實作時遇到兩個問題:

1、scrollToPosition(int position) 捲動的位置不夠精準。
2、版面一複雜,若 RecyclerView 寬度採用自適應或權重百分比,header 可能出現空白。

加上該專案作者已停止維護,因此改回 StickyListHeadersListView。

在 Android Studio 中引入

// build.gradle 的 dependencies 區塊加入
compile 'se.emilsjolander:stickylistheaders:2.7.0'

版面中替換 ListView

<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 需實作的介面

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 只負責呼叫與呈現,雙向聯動與資料一致性自然就成立了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved