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

Android 元件化開發(一):封裝可複用的底部彈出式選單

編輯:關於 Android 程式設計

元件化開發,融入 Android

引言

App 裡到處看得到從底部彈出的選單,手機 QQ 與微信更換頭像時的那個就是標準範例。這類互動實在太常見,值得抽成一個獨立元件——封裝好之後,使用起來就和系統原生 View 一樣直觀,可擴展性與可維護性都跟著上來。

一、先把效果做出來

Android 裡做彈出層一般有兩條路:Dialog 與 PopupWindow。這裡選 PopupWindow,因為它更輕、位置更好控制。

建立 PopupWindow 的程式碼:

View view = mInflater.inflate(R.layout.bottom_pop_window, null);
mPopupWindow = new PopupWindow(view,
        ScreenUtil.getScreenWidth(mContext),
        LinearLayout.LayoutParams.WRAP_CONTENT);

// 監聽 dismiss,關閉時把螢幕亮度還原
mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
    @Override
    public void onDismiss() {
        params.alpha = 1.0f;
        window.setAttributes(params);
    }
});

mPopupWindow.setWidth(LayoutParams.MATCH_PARENT);
mPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
mPopupWindow.setTouchable(true);
mPopupWindow.setFocusable(true);
mPopupWindow.setOutsideTouchable(true);
// 從底部彈起的動畫
mPopupWindow.setAnimationStyle(R.style.popWindow_animation);

對應的版面配置:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:orientation="vertical"
    android:padding="@dimen/mg_20">

    <TextView
        android:id="@+id/tv_take_photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:gravity="center"
        android:padding="@dimen/mg_15"
        android:textColor="@color/black_65"
        android:textSize="@dimen/ts_2" />

    <TextView
        android:id="@+id/tv_choose_photo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:gravity="center"
        android:padding="@dimen/mg_15"
        android:textColor="@color/black_65"
        android:textSize="@dimen/ts_2" />

    <TextView
        android:id="@+id/tv_cancel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/mg_15"
        android:background="@color/white"
        android:gravity="center"
        android:padding="@dimen/mg_15"
        android:text="@string/ddc_dialog_cancel"
        android:textColor="@color/black_65"
        android:textSize="@dimen/ts_2" />
</LinearLayout>

還有一個細節:正常的底部選單彈出時,背景會變暗;關閉後亮度恢復。Dialog 自帶這個效果,PopupWindow 沒有,得自己做。做法是直接動 Window 的 alpha:

// 1. 取得 WindowManager
WindowManager windowManager = context.getWindowManager();
// 2. 取得 Window 與其 LayoutParams
Window window = context.getWindow();
LayoutParams params = context.getWindow().getAttributes();
// 3. 調整 alpha 控制明暗
params.alpha = 0.5f;
window.setAttributes(params);

二、動手封裝

只做效果是不夠的。每次要用都貼一大段程式碼,其中九成還是重複的,完全沒有意義。正確做法是把不變的部分收進元件內部,把會變的部分以回呼形式交給外部決定。

分析

仔細看,每次使用這個元件,真正不同的只有兩件事:按鈕上的文字,以及按下按鈕之後要做什麼。相同的則是彈窗的建立、顯示、關閉以及背景明暗處理。所以只要把這兩個變數抽成方法與抽象回呼即可。

封裝中

新增一個 BottomPopView 類,把 PopupWindow 的初始化作業全部藏在內部,對外只暴露設定文字的方法與兩個點擊回呼。

public abstract class BottomPopView {

    private Context mContext;
    private View anchor;
    private LayoutInflater mInflater;
    private TextView mTvTop;
    private TextView mTvBottom;
    private TextView mTvCancel;
    private PopupWindow mPopupWindow;

    LayoutParams params;
    WindowManager windowManager;
    Window window;

    /**
     * @param context 宿主 Activity
     * @param anchor  依附在哪個 View 之下
     */
    public BottomPopView(Activity context, View anchor) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(context);
        this.anchor = anchor;
        windowManager = context.getWindowManager();
        window = context.getWindow();
        params = context.getWindow().getAttributes();
        init();
    }

    public void init() {
        View view = mInflater.inflate(R.layout.bottom_pop_window, null);
        params.dimAmount = 0.5f;
        window.addFlags(LayoutParams.FLAG_DIM_BEHIND);

        mTvTop = (TextView) view.findViewById(R.id.tv_take_photo);
        mTvBottom = (TextView) view.findViewById(R.id.tv_choose_photo);
        mTvCancel = (TextView) view.findViewById(R.id.tv_cancel);

        mTvTop.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View arg0) { onTopButtonClick(); }
        });
        mTvBottom.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View arg0) { onBottomButtonClick(); }
        });
        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) { dismiss(); }
        });

        mPopupWindow = new PopupWindow(view,
                ScreenUtil.getScreenWidth(mContext),
                LinearLayout.LayoutParams.WRAP_CONTENT);

        // dismiss 時還原螢幕亮度
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                window.setAttributes(params);
            }
        });

        mPopupWindow.setWidth(LayoutParams.MATCH_PARENT);
        mPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        // 從底部彈起的動畫
        mPopupWindow.setAnimationStyle(R.style.popWindow_animation);
    }

    /** 顯示底部選單 */
    public void show() {
        mPopupWindow.showAtLocation(anchor, Gravity.BOTTOM, 0, 0);
        params.alpha = 0.5f;
        window.setAttributes(params);
    }

    /** 第一個按鈕被點擊的回呼 */
    public abstract void onTopButtonClick();

    /** 第二個按鈕被點擊的回呼 */
    public abstract void onBottomButtonClick();

    public void setTopText(String text) {
        mTvTop.setText(text);
    }

    public void setBottomText(String text) {
        mTvBottom.setText(text);
    }

    public void dismiss() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
    }
}

設計重點就兩個:setTopText() 與 setBottomText() 讓外部決定文字;onTopButtonClick() 與 onBottomButtonClick() 讓外部決定行為。

像用系統原生 View 一樣使用

封裝完成後,呼叫端乾淨得多了:

bottomPopView = new BottomPopView(this, root) {
    @Override
    public void onTopButtonClick() {
        takePhoto();          // 拍照
    }

    @Override
    public void onBottomButtonClick() {
        choosePhoto();        // 選取本地圖片
    }
};
bottomPopView.setTopText("拍照");
bottomPopView.setBottomText("選擇圖片");
bottomPopView.show();

以後再遇到需要底部彈出選單的場合,這幾行就搞定了。

還可以再往下想

這個版本用抽象類搭配匿名內部實作,寫起來輕巧,但仍有改進空間:按鈕數量被寫死成兩個,若某個頁面需要三個選項就得改元件;文字設定用的是 String,多語言專案會不方便,改收 int stringRes 會更好;另外 params 與 window 直接從 Activity 取,意味著這個元件離不開 Activity 環境,若要給 Fragment 或 Dialog 使用,得再抽一層。

這些都是元件化過程中會反覆遇到的取捨。先讓它能用、能被複用,再依實際需求逐步開孔——這比一開始就追求完美更容易落地。

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