編輯:關於 Android 程式設計
在行動端,從螢幕底部滑出一列選項的互動模式幾乎成了共識。iOS 稱它 ActionSheet,網頁端叫「彈出菜單」,Android 上最直接的實作工具是 PopupWindow。這次就以 iOS 裡「更換頭像」的選擇流程為範本,做一個視覺與手感都接近的版本。

整段開啟邏輯並不長,先貼出來,再逐項拆解:
private void openPopupWindow(View v) {
// 防止連點造成重複彈出
if (popupWindow != null && popupWindow.isShowing()) {
return;
}
View view = LayoutInflater.from(this).inflate(R.layout.view_popupwindow, null);
popupWindow = new PopupWindow(view,
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
// 必須設定背景,否則會報錯;同時讓點擊外部可關閉
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
popupWindow.setAnimationStyle(R.style.PopupWindow);
popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, navigationHeight);
popupWindow.setOnDismissListener(this);
setOnPopupViewClick(view);
setBackgroundAlpha(0.5f); // 彈出時把背景壓暗
}
PopupWindow 的內容就是一個普通布局,跟寫 Activity 沒兩樣。這裡分兩個圓角卡片:上面一張放說明文字與兩個操作項,下面一張單獨放「取消」——刻意分開是為了做出 iOS 那種卡片之間留有間隙的層次感。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:background="@drawable/popup_shape"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="16dp"
android:text="你可以將照片上傳至照片牆"
android:textColor="#666"
android:textSize="14sp" />
<View
android:layout_width="match_parent"
android:layout_height="0.1dp"
android:background="#888" />
<TextView
android:id="@+id/tv_pick_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="16dp"
android:text="從手機相冊選擇"
android:textColor="#118"
android:textSize="18sp" />
<!-- 分隔線與第二個選項 -->
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:background="@drawable/popup_shape">
<TextView
android:id="@+id/tv_cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="16dp"
android:text="取消"
android:textColor="#118"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
圓角由 popup_shape.xml 提供,一個簡單的 shape 即可:<solid> 填底色,<corners> 給 12dp 圓角。分隔線這裡用 0.1dp 的 View 硬畫,是為了避開不同解析度下 1dp 偏粗的問題。

寫法和建立一般控件一樣,關鍵在寬高參數:寬度給 MATCH_PARENT 讓它橫向鋪滿,高度給 WRAP_CONTENT 由內容決定。
View view = LayoutInflater.from(this).inflate(R.layout.view_popupwindow, null);
popupWindow = new PopupWindow(view,
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
這裡有個一定要記的細節:必須呼叫 setBackgroundDrawable。看起來只是給了個透明 Drawable,但若省略,點擊外部關閉的能力會失效,部分系統上還會拋出異常。
在 res 下建立 anim 目錄,分別寫入場與出場動畫:
<!-- res/anim/window_in.xml -->
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:duration="300"
android:shareInterpolator="true">
<translate android:fromYDelta="100%" android:toYDelta="0" />
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" />
</set>
<!-- res/anim/window_out.xml -->
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:duration="300"
android:shareInterpolator="true">
<translate android:fromYDelta="0" android:toYDelta="100%" />
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" />
</set>
再用一個 style 把兩者綁起來:
<style name="PopupWindow">
<item name="android:windowEnterAnimation">@anim/window_in</item>
<item name="android:windowExitAnimation">@anim/window_out</item>
</style>
popupWindow.setAnimationStyle(R.style.PopupWindow);
彈出時把整頁透明度降到 0.5,關閉時恢復為 1,層次感立刻出來。這裡調整的是 Activity 的 window alpha:
public void setBackgroundAlpha(float alpha) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = alpha;
getWindow().setAttributes(lp);
}
@Override
public void onDismiss() {
setBackgroundAlpha(1f);
}
實作 onDismissListener 是關鍵——少了它,關掉彈窗之後畫面會一直停在半透明的狀態。
private void setOnPopupViewClick(View view) {
TextView tvPickPhone = view.findViewById(R.id.tv_pick_phone);
TextView tvPickZone = view.findViewById(R.id.tv_pick_zone);
TextView tvCancel = view.findViewById(R.id.tv_cancel);
tvPickPhone.setOnClickListener(this);
tvPickZone.setOnClickListener(this);
tvCancel.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_pick_phone:
Toast.makeText(this, "從手機相冊選擇", Toast.LENGTH_SHORT).show();
popupWindow.dismiss();
break;
case R.id.tv_pick_zone:
Toast.makeText(this, "從空間相冊選擇", Toast.LENGTH_SHORT).show();
popupWindow.dismiss();
break;
case R.id.tv_cancel:
popupWindow.dismiss();
break;
}
}
注意這裡的 findViewById 是從傳入的 view 上找,不是從 Activity 找。寫錯成 Activity 的 findViewById 會直接拿到 null。
有虛擬導覽鍵的手機上,若把彈窗貼齊螢幕底部,會被導覽鍵遮住一半。可以透過系統內建的 dimen 資源讀出導覽鍵高度:
int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
navigationHeight = getResources().getDimensionPixelSize(resourceId);
接著依是否存在導覽鍵決定偏移量:
// 有導覽鍵 popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, navigationHeight); // 沒有導覽鍵 popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
更穩妥的判斷方式是讀取 ViewConfiguration 或檢查是否有 navigation_bar 資源的強制顯示標誌,這裡為了示範先假設存在。
public class MainActivity extends AppCompatActivity
implements View.OnClickListener, PopupWindow.OnDismissListener {
private Button btOpen;
private PopupWindow popupWindow;
private int navigationHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btOpen = findViewById(R.id.bt_open);
btOpen.setOnClickListener(this);
int resourceId = getResources().getIdentifier(
"navigation_bar_height", "dimen", "android");
navigationHeight = getResources().getDimensionPixelSize(resourceId);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.bt_open) {
openPopupWindow(v);
}
}
@Override
public void onDismiss() {
setBackgroundAlpha(1f);
}
}
Android 記事本 App 實作教學(含到點提醒功能)
本文示範一個完整的記事本 App:清單依日期分組、可新增與編輯、長按可刪除,並且能在指定時間跳出提醒視窗並播放鈴聲。以下依檔案說明重點。 MainActivity.jav
深入解析 Android 中的 Builder 建造者模式
在 Android 原始碼中,設計模式無所不在。其中,建造者模式因為能優雅地封裝複雜物件的建立流程,經常出現在各種框架與元件中。本文以 AlertDialog 為例,說明
用 Vitamio 打造萬能播放器(3):Fragment + ViewPager 搭主界面與本地清單
前言 要做出一個真正好用的 Android 播放器,需要處理的功能與細節多到超出想像,牽涉的知識面也很廣。本章先用 Fragment 搭配 ViewPager 把主界面架
Android 中的 AES 加解密實作:一個能真正跑通的工具類
在專案裡加入 AES 加解密時,網路上找得到的範例多到嚇人,但真正能跑通的少得驚人。常見的失敗模式有兩種:一是加密字串在 Java 端解不開,二是同一份程式碼換到不同裝置