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

Android 仿外賣購物車實作全解:懸停標題、左右聯動與拋物線動畫

編輯:關於 Android 程式設計

效果預覽

先盤點技術點

畫面看起來熱鬧,但真正需要花心思的其實就這幾塊:

- 清單標題懸停
- 左右兩欄滑動聯動
- 加入商品時的拋物線動畫
- 底部彈出購物車清單
- 資料同步與畫面刷新

除此之外,還有幾個實作時一定會踩到的坑。版面本身不複雜,我們直接進程式碼。

一、清單標題懸停

現在做專案幾乎都從 ListView 換成 RecyclerView 了。上一篇的懸停標題用的是開源專案 sticky-headers-recyclerview,但這次實作時遇到兩個問題:

一是 scrollToPosition(int position) 捲動到的位置不準;二是當版面結構複雜一點、RecyclerView 寬度自適應或用了權重百分比時,header 可能顯示成空白。加上該專案作者已停止維護,所以這次換回 StickyListHeadersListView。

StickyListHeadersListView 基本用法

Android Studio 專案在 gradle 的 dependencies 中加入:

compile 'se.emilsjolander:stickylistheaders:2.7.0'

版面檔用 StickyListHeadersListView 取代 ListView:

<se.emilsjolander.stickylistheaders.StickyListHeadersListView
    android:background="#fff"
    android:id="@+id/itemListView"
    android:layout_height="match_parent"
    android:layout_width="match_parent" />

Adapter 同時繼承 BaseAdapter 並實作 StickyListHeadersAdapter 介面,該介面只有兩個方法:

View getHeaderView(int position, View convertView, ViewGroup parent);
long getHeaderId(int position);

其餘用法與 ListView 相同,另外多了幾個專屬方法,看名字就知道用途:

void setAreHeadersSticky(boolean areHeadersSticky);
boolean areHeadersSticky();
void setOnHeaderClickListener(OnHeaderClickListener listener);
void setOnStickyHeaderChangedListener(OnStickyHeaderChangedListener listener);
View getListChildAt(int index);
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);
    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);
    set.addAnimation(new AlphaAnimation(0, 1));
    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);
    set.addAnimation(new AlphaAnimation(1, 0));
    set.setDuration(500);
    return set;
}

// 套用動畫,再切換可見性
tvMinus.setAnimation(getHiddenAnimation());
tvMinus.setVisibility(View.GONE);

拋物線動畫

拋物線可以拆成兩個平移動畫,差別只在插值器:X 軸用線性,Y 軸用加速。

還有個容易忽略的細節:由於動畫路徑跨度大,這個動畫必須掛在整體版面的根容器上,寫在清單 item 裡會被裁切顯示不全。程式碼中的 anim_mask_layout 就是根 RelativeLayout。

實作步驟:

1、點擊加號時,取得控制項在螢幕上的絕對座標,回呼 Activity 播放動畫。

int[] loc = new int[2];
v.getLocationInWindow(loc);
activity.playAnimation(loc);

2、建立動畫用的 View 並加入根容器,動畫結束後移除。

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());     // X 軸線性

    Animation translationY = new TranslateAnimation(0, 0, 0, des[1] - startY);
    translationY.setInterpolator(new AccelerateInterpolator()); // Y 軸加速,形成拋物線感

    set.addAnimation(translationX);
    set.addAnimation(translationY);
    set.addAnimation(new AlphaAnimation(1, 0.5f));
    set.setDuration(500);
    return set;
}

// 計算動畫 View 在根容器中的座標後加入
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 onAnimationRepeat(Animation animation) { }
        @Override
        public void onAnimationEnd(final Animation animation) {
            // 直接 remove 可能因為畫面仍在繪製中而報錯,延遲一點比較安全
            mHandler.postDelayed(new Runnable() {
                @Override public void run() { anim_mask_layout.removeView(v); }
            }, 100);
        }
    });
    v.startAnimation(set);
}

四、底部彈出購物車清單

官方沒有提供現成的底部彈出控制項,自己寫又要兼顧流順與可移植性,因此建議直接用第三方庫。這裡推薦 bottomsheet,整合簡單、效果多樣。

compile 'com.flipboard:bottomsheet-core:1.5.1'

版面中用 BottomSheetLayout 包住「彈出時要變暗的背景內容」,它本質上就是 FrameLayout 的延伸:

<com.flipboard.bottomsheet.BottomSheetLayout
    android:id="@+id/bottomSheetLayout"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">

    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="horizontal">
        <!-- 原本的內容 -->
    </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 取值,也能用位置取值,效能比 HashMap 好,是官方推薦的做法;SparseIntArray 則對應 HashMap<Integer, Integer>。

把加減邏輯全部集中在 Activity,清單顯示的數量一律向 Activity 索取,避免各處各存一份而對不上:

/** 商品購買數量 +1 */
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);
}

/** 依商品 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);
}

/** 刷新總價、數量等 UI */
private void update(boolean refreshGoodList) { ... }

關鍵是把「資料的真實來源」收斂到一處,其餘元件都只讀不寫,畫面自然就不容易錯亂。若有更簡潔的實作,也歡迎交流。

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