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

Android Dialog 實戰大全:從系統彈窗到自定義底部菜單

編輯:關於 Android 程式設計

做 Android 開發,Dialog 幾乎是繞不開的一塊。提示確認要用它,底部彈出的操作面板要用它,仿 Toolbar 菜單也要用它。但 Dialog 的玩法實在太多,每次要用都得翻半天資料,還常常踩坑——比如設定了寬高卻沒生效。這篇文章把常見套路整理成一套可以照抄的實踐方案。

一、最基礎的系統 Dialog

最簡單的就是 AlertDialog,配合 Builder 設定標題、內容與按鈕:

findViewById(R.id.btn_common).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("普通的對話框的標題");
        builder.setMessage("這是一個普通的對話框的內容");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                toast("取消");
            }
        });
        builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                toast("確定");
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
});

效果就是系統預設的那種樣式:

二、修改位置、大小與透明度

關鍵點在於:必須在 show() 之後去拿到 Window 並修改它的屬性,否則寬高之類的設定完全不會生效。這是很多人踩的第一個坑。

// 放在 show() 之後,否則 height、width 等屬性不生效
Window dialogWindow = dialog.getWindow();
WindowManager m = getWindowManager();
Display d = m.getDefaultDisplay();
WindowManager.LayoutParams p = dialogWindow.getAttributes();

p.height = (int) (d.getHeight() * 0.4);   // 高度為屏幕的 40%
p.width  = (int) (d.getWidth()  * 0.6);   // 寬度為屏幕的 60%
p.gravity = Gravity.BOTTOM;               // 位置貼底
p.alpha = 0.5f;                           // 半透明
dialogWindow.setAttributes(p);

這段代碼把對話框壓成了屏幕下方一個半透明的扁塊:

WindowManager.LayoutParams 裡可用的屬性還有很多,這裡只列最常用的一小部分,其餘可以自行試。

三、給 Dialog 塞自定義佈局

先寫一個簡單的自定義佈局 dialog_custom1.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="#00ff00">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textColor="#ff0000"
        android:text="你好" />
</LinearLayout>

然後用 setView() 把它塞進 Builder:

findViewById(R.id.btn_custom2).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setView(R.layout.dialog_custom1);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
});

跑起來發現醜得驚人:

問題出在 AlertDialog 的預設主題上——它自帶一塊灰色背景還有一圈邊距。要徹底擺脫這副樣子,得換主題。

四、自定義主題讓 Dialog 變乾淨

在 values/styles.xml 中新建一個基於 android:Theme.Dialog 的樣式:

<style name="MyCommonDialog" parent="android:Theme.Dialog">
    <!-- 背景顏色及透明程度 -->
    <item name="android:windowBackground">@android:color/transparent</item>
    <!-- 是否半透明 -->
    <item name="android:windowIsTranslucent">false</item>
    <!-- 是否去掉標題 -->
    <item name="android:windowNoTitle">true</item>
    <!-- 是否浮在 Activity 之上 -->
    <item name="android:windowIsFloating">true</item>
    <!-- 是否打暗背景 -->
    <item name="android:backgroundDimEnabled">false</item>
    <!-- 背景變暗的透明度 -->
    <item name="android:backgroundDimAmount">0.5</item>
</style>

建立時把主題傳進構造方法:

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.MyCommonDialog);

這下灰色的外套沒了:

但仍有問題:佈局裡寫的 100dp 寬高還是沒生效。原因在於子 View 的尺寸是由父容器測量的,而 setView() 塞進去的佈局直接掛在了一個 FrameLayout 上,LinearLayout 的 layout_width/height 被父容器忽略了。

解法很樸素:在最外層再套一個 RelativeLayout,並用 layout_centerInParent 讓內容居中。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_centerInParent="true"
        android:background="#00ff00">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="你好"
            android:textColor="#ff0000" />
    </LinearLayout>
</RelativeLayout>

到這裡,主題 + 自定義佈局的組合拳就打通了,各種花樣對話框都能照這個套路做。

五、繼承 Dialog:一次封裝,到處复用

如果某種對話框要反覆用,更省事的做法是寫一個子類,把主題和位置都在構造與 onCreate 裡預先設定好。

public class MyDialog extends Dialog {

    // 預加載樣式,這樣就不必每次建立時都指定主題
    public MyDialog(Context context) {
        this(context, R.style.MyDialog);
    }

    public MyDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window dialogWindow = getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes();
        p.x = 0;
        p.y = 100;
        p.gravity = Gravity.LEFT | Gravity.TOP;
        dialogWindow.setAttributes(p);
    }
}

關於 p.x 與 p.y 的含義,值得記一下:

* 兩者表示相對於原始位置的偏移量
* 包含 Gravity.LEFT 時對話框出現在左側,p.x 為相對左邊的偏移,負值忽略
* 包含 Gravity.RIGHT 時出現在右側,p.x 為相對右邊的偏移
* 包含 Gravity.TOP 時出現在頂部,p.y 為相對頂部的偏移
* 包含 Gravity.BOTTOM 時出現在底部,p.y 為相對底部的偏移
* 包含 Gravity.CENTER_HORIZONTAL 時水平居中,p.x 正值右移、負值左移
* 包含 Gravity.CENTER_VERTICAL 時垂直居中,p.y 正值下移、負值上移
* gravity 預設為 CENTER,即水平與垂直雙向居中

使用時只要 new 一下並 setContentView:

findViewById(R.id.btn_custom3).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        MyDialog dialog = new MyDialog(MainActivity.this);
        dialog.setContentView(R.layout.dialog_custom2);
        dialog.show();
    }
});

六、給 Dialog 加上進出動畫

先寫兩個補間動畫。dialog_enter.xml 從下方滑入:

<set xmlns:android="https://schemas.android.com/apk/res/android">
    <translate
        android:duration="200"
        android:fillAfter="true"
        android:fromYDelta="100%p"
        android:toYDelta="0%" />
</set>

dialog_exit.xml 往下滑出:

<set xmlns:android="https://schemas.android.com/apk/res/android">
    <translate
        android:duration="200"
        android:fillAfter="true"
        android:fromYDelta="0%"
        android:toYDelta="100%p" />
</set>

再在 styles.xml 裡把動畫掛到主題上:

<style name="MyAnimDialog" parent="android:Theme.Dialog">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowIsTranslucent">false</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">true</item>
    <item name="android:backgroundDimAmount">0.5</item>
    <item name="android:windowAnimationStyle">@style/dialog_animation</item>
</style>

<style name="dialog_animation">
    <item name="android:windowEnterAnimation">@anim/dialog_enter</item>
    <item name="android:windowExitAnimation">@anim/dialog_exit</item>
</style>

核心就是 android:windowAnimationStyle,引用方式和前面完全一致:

七、底部彈出的 Dialog

把「預加載佈局 + 綁定點擊 + 設定位置尺寸」三件事都塞進構造方法,調用方就一行代碼搞定:

public class MyBottomDialog extends Dialog {

    public MyBottomDialog(Context context) {
        this(context, R.style.MyAnimDialog);
    }

    public MyBottomDialog(Context context, int themeResId) {
        super(context, themeResId);

        // 加載佈局並綁定點擊事件
        View contentView = getLayoutInflater().inflate(R.layout.dialog_custom3, null);
        contentView.findViewById(R.id.tv_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "你好", Toast.LENGTH_SHORT).show();
            }
        });
        super.setContentView(contentView);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window dialogWindow = getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes();
        WindowManager m = getWindow().getWindowManager();
        Display d = m.getDefaultDisplay();

        p.height = (int) (d.getHeight() * 0.6);
        p.width = d.getWidth();
        p.gravity = Gravity.LEFT | Gravity.BOTTOM;
        dialogWindow.setAttributes(p);
    }
}

調用時不用再操心佈局:

findViewById(R.id.btn_custom5).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        MyBottomDialog dialog = new MyBottomDialog(MainActivity.this);
        dialog.show();
    }
});

八、仿 Menu 的彈出菜單

做法與上面同理,重點是利用 DisplayMetrics 拿到屏幕密度,再把偏移量換算成 dp,讓菜單準確貼在指定位置:

public class MyMenuDialog extends Dialog {

    public MyMenuDialog(Context context) {
        this(context, R.style.MyDialog);
    }

    public MyMenuDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window dialogWindow = getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes();

        WindowManager m = getWindow().getWindowManager();
        Display d = m.getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        d.getMetrics(outMetrics);

        p.x = (int) (15 * outMetrics.density);   // 水平偏移 15dp
        p.y = (int) (45 * outMetrics.density);   // 垂直偏移 45dp
        p.gravity = Gravity.RIGHT | Gravity.TOP;
        dialogWindow.setAttributes(p);
    }
}

如果再掛上一個進場動畫,一個像樣的菜單彈窗就成型了:

思路總結

回頭看,Dialog 的自定義其實就三條主線:

1. 主題——用 style 去掉系統的默認背景、標題、變暗效果;
2. 佈局——setView 塞自定義 xml,記得最外層套 match_parent 的容器,否則子佈局的寬高不生效;
3. 位置與尺寸——在 show() 之後通過 WindowManager.LayoutParams 調整 gravity、x/y、width/height、alpha。

至於帶 ListView、GridView 的複雜彈窗,無非就是把列表塞進自定義佈局再繼承一次 Dialog,依葫蘆畫瓢即可。

完整示例代碼:https://github.com/cskun/DialogDemo

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