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

用 PopupWindow 實作左側彈出菜單:進出動畫與點擊外部自動關閉

編輯:關於 Android 程式設計

PopupWindow 最適合拿來做浮層效果。它的主要能力包括:以任意自訂 View 作為內容(透過 LayoutInflater 載入)、為出現與退出指定動畫、以及自由指定顯示位置。

為了把這些功能一次展示清楚,又不讓程式碼變得複雜,下面實作一個「點擊按鈕後從左側彈出菜單」的完整範例,並加上進出動畫與點擊其他區域自動關閉的行為。

1. PopwindowOnLeftActivity.java

package com.pop.main;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.PopupWindow;

public class PopwindowOnLeftActivity extends Activity {

    private PopupWindow popupWindow;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // 點擊按鈕彈出菜單
        Button pop = (Button) findViewById(R.id.popBtn);
        pop.setOnClickListener(popClick);
    }

    // 點擊後顯示左側菜單
    OnClickListener popClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            getPopupWindow();
            // 顯示在按鈕的左下方
            popupWindow.showAsDropDown(v);
            // 其他顯示方式可嘗試:
            // popupWindow.showAsDropDown(v, (screenWidth - dialogWidth) / 2, 0);
            // popupWindow.showAtLocation(findViewById(R.id.layout), Gravity.CENTER, 0, 0);
        }
    };

    /** 建立 PopupWindow */
    protected void initPopupWindow() {
        // 載入自訂布局 pop.xml
        View popupWindow_view = getLayoutInflater().inflate(R.layout.pop, null, false);

        // 200、150 為寬與高,最後的 true 表示可 focus
        popupWindow = new PopupWindow(popupWindow_view, 200, 150, true);

        // 設定動畫樣式
        popupWindow.setAnimationStyle(R.style.AnimationFade);

        // 點擊其他地方自動消失
        popupWindow_view.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                    popupWindow = null;
                }
                return false;
            }
        });

        // pop.xml 中的控制項
        Button open  = (Button) popupWindow_view.findViewById(R.id.open);
        Button save  = (Button) popupWindow_view.findViewById(R.id.save);
        Button close = (Button) popupWindow_view.findViewById(R.id.close);

        open.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("打開操作");
                popupWindow.dismiss();
            }
        });

        save.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("保存操作");
                popupWindow.dismiss();
            }
        });

        close.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("關閉操作");
                popupWindow.dismiss();
            }
        });
    }

    /** 取得 PopupWindow 實例 */
    private void getPopupWindow() {
        if (null != popupWindow) {
            popupWindow.dismiss();
            return;
        } else {
            initPopupWindow();
        }
    }
}

2. main.xml(主要介面)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/popBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/pop_left" />
</LinearLayout>

3. pop.xml(彈出層布局)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/darker_gray">

    <Button
        android:id="@+id/open"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/btn"
        android:text="@string/open" />

    <Button
        android:id="@+id/save"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/btn"
        android:text="@string/save" />

    <Button
        android:id="@+id/close"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/btn"
        android:text="@string/close" />
</LinearLayout>

4. values 下的 style

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AnimationFade">
        <!-- PopupWindow 左右彈出的效果 -->
        <item name="android:windowEnterAnimation">@anim/in_lefttoright</item>
        <item name="android:windowExitAnimation">@anim/out_righttoleft</item>
    </style>
</resources>

5. values 下的 string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, PopwindowOnLeftActivity!</string>
    <string name="app_name">PopwindowOnLeft</string>
    <string name="pop_left">彈出左側菜單</string>
    <string name="open">打開</string>
    <string name="save">保存</string>
    <string name="close">關閉</string>
</resources>

6. anim/in_lefttoright.xml(出現:由左而右)

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <!-- 定義從左向右進入的動畫 -->
    <translate
        android:fromXDelta="-100%"
        android:toXDelta="0"
        android:duration="500" />
</set>

7. anim/out_righttoleft.xml(退出:由右而左)

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <!-- 定義從右向左的退出動畫 -->
    <translate
        android:fromXDelta="0"
        android:toXDelta="-100%"
        android:duration="500" />
</set>

幾個實作重點

顯示位置有兩種寫法。showAsDropDown(view) 以觸發它的那個 View 為基準,把浮層貼在其左下角;若需要置中或自訂偏移,改用 showAtLocation(view, gravity, x, y),最後兩個參數就是水平與垂直偏移量。

「點擊外部關閉」其實要綁在內容 View 上。PopupWindow 若設為可 focus(建構子最後參數為 true),外部觸摸事件會落到浮層自身的內容 View,因此在 popupWindow_view 上掛 OnTouchListener 並呼叫 dismiss() 就能達成點擊外部關閉的效果。

動畫只認 style,不認檔名。兩個 anim 檔本身不會生效,必須透過 setAnimationStyle() 指向那個設定了 windowEnterAnimation 與 windowExitAnimation 的 style 才會被套用。

記得釋放引用。這裡在 dismiss 後把 popupWindow 設為 null,下次點擊才會重新 inflate;否則重複使用同一個已銷毀的實例會出現狀態錯亂。

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