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

Android AlertDialog 進階玩法:做出分享、退出、下載風格彈窗

編輯:關於 Android 程式設計

摘要

彈窗常用來引導使用者做某個操作:點分享鈕彈出分享面板、雙擊返回鈕彈出退出確認、點下載彈出下載提示。這三種情境都能直接用 AlertDialog 完成。

一、AlertDialog 基礎

AlertDialog 不能用 new 直接建立,必須透過 new AlertDialog.Builder(...).create()。那屬性要怎麼設?有兩種寫法。

寫法一:在 Dialog 物件上設定

private void showDialog() {
    AlertDialog mDialog = new AlertDialog.Builder(this).create();
    mDialog.setIcon(R.drawable.ic_launcher);
    mDialog.setTitle("系統提示");
    mDialog.setMessage("你確定要退出嗎?");
    mDialog.setButton(DialogInterface.BUTTON_POSITIVE, "確定",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
    mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
        new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
            }
        });
    mDialog.show();
}

寫法二:在 Builder 上設定

private void showDialog() {
    Builder mBuilder = new AlertDialog.Builder(this);
    mBuilder.setIcon(R.drawable.ic_launcher);
    mBuilder.setTitle("系統提示");
    mBuilder.setMessage("你確定要退出嗎?");
    mBuilder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }
    });
    mBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
        }
    });
    AlertDialog mDialog = mBuilder.create();
    mDialog.show();
}

兩者效果相同:視窗水平垂直置中,左右留有空隙。

二、改造預設樣子

要做出「從底部彈出、寬度填滿螢幕、高度依內容自適應」的效果,三步走:建立 Dialog → 自訂內容 View → 設定 Window 屬性。

方式一:setLayout()

View view = getLayoutInflater().inflate(R.layout.popup_dialog, null);
AlertDialog mDialog = new AlertDialog.Builder(this).create();
mDialog.show();   // 必須先 show,才能取得 Window

Window window = mDialog.getWindow();
window.setGravity(Gravity.BOTTOM);
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                 WindowManager.LayoutParams.WRAP_CONTENT);

方式二:setAttributes()

View view = getLayoutInflater().inflate(R.layout.popup_dialog, null);
AlertDialog mDialog = new AlertDialog.Builder(this).create();
mDialog.show();

Window window = mDialog.getWindow();
window.setGravity(Gravity.BOTTOM);

WindowManager.LayoutParams p = window.getAttributes();
p.width = WindowManager.LayoutParams.MATCH_PARENT;
p.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(p);

方式三:指定實際像素值

View view = getLayoutInflater().inflate(R.layout.popup_dialog, null);
AlertDialog mDialog = new AlertDialog.Builder(this).create();
mDialog.show();

Window window = mDialog.getWindow();
window.setGravity(Gravity.BOTTOM);

WindowManager manager = getWindowManager();
Display display = manager.getDefaultDisplay();
int width = display.getWidth();
int height = 300;   // 自訂高度
window.setLayout(width, height);

關鍵細節:show() 一定要寫在取得 Window 之前,因為 Dialog 尚未顯示時 Window 還沒附加到視窗管理器,設定會失效。

三、加入彈窗動畫

Android 基本動畫有平移、漸變、縮放、旋轉與組合動畫。底部彈出用平移最合適。

<!-- enter_dialog_anim.xml -->
<translate xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fromYDelta="100%" />

<!-- exit_dialog_anim.xml -->
<translate xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="300"
    android:toYDelta="100%" />

在 style.xml 中把進出動畫綁成一個樣式:

<style name="popup_style" parent="android:Animation">
    <item name="@android:windowEnterAnimation">@anim/enter_dialog_anim</item>
    <item name="@android:windowExitAnimation">@anim/exit_dialog_anim</item>
</style>

套用時同時指定內容 View 與動畫:

window.setContentView(view);                    // 不設定就不會顯示內容
window.setWindowAnimations(R.style.popup_style); // 套用動畫

四、另一條路:自訂 Activity 當彈窗

用一個 Activity 搭配 Dialog 主題,也能做出完全一樣的效果,而且自由度更高。

步驟一:popup_main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/transparent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/share_weibo_tv"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/share_padding"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="@string/weibo" />

        <TextView
            android:id="@+id/share_weixin_tv"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/share_padding"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="@string/weixin" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/share_kongjian_tv"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/share_padding"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="@string/kongjian" />

        <TextView
            android:id="@+id/share_qq_tv"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/share_padding"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="@string/qq" />
    </LinearLayout>

    <Button
        android:id="@+id/cancel_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/activity_vertical_margin"
        android:background="@drawable/btn_bg"
        android:text="@string/cancel" />
</LinearLayout>

步驟二:定義 Dialog 主題並在 Manifest 掛上

<style name="Theme.CustomDialog" parent="@android:style/Theme.Dialog">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowFullscreen">true</item>
</style>

<activity android:name="MyDialogActivity"
    android:theme="@style/Theme.CustomDialog" />

步驟三:MyDialogActivity

package cn.teachcourse.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class MyDialogActivity extends Activity implements OnClickListener {

    private View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = getLayoutInflater().inflate(R.layout.popup_main, null, false);
        setContentView(view);
        initView();
    }

    private void initView() {
        Window window = getWindow();
        window.setLayout(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.popup_style);

        TextView weibo_tv = (TextView) view.findViewById(R.id.share_weibo_tv);
        TextView weixin_tv = (TextView) view.findViewById(R.id.share_weixin_tv);
        TextView qq_tv = (TextView) view.findViewById(R.id.share_qq_tv);
        TextView kongjian_tv = (TextView) view.findViewById(R.id.share_kongjian_tv);
        Button cancel_btn = (Button) view.findViewById(R.id.cancel_btn);

        weibo_tv.setOnClickListener(this);
        weixin_tv.setOnClickListener(this);
        qq_tv.setOnClickListener(this);
        kongjian_tv.setOnClickListener(this);
        cancel_btn.setOnClickListener(this);

        abjustDrawablePos(weibo_tv, R.drawable.share_weibo);
        abjustDrawablePos(weixin_tv, R.drawable.share_weixin);
        abjustDrawablePos(kongjian_tv, R.drawable.share_kongjian);
        abjustDrawablePos(qq_tv, R.drawable.share_qq);
    }

    /** 加入圖示並置中裁切 */
    @SuppressLint("ResourceAsColor")
    private void abjustDrawablePos(TextView tv, int resId) {
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), resId);
        bmp = centerSquareScaleBitmap(bmp, 250);
        Drawable drawable = new BitmapDrawable(bmp);
        drawable.setBounds(0, 0, 0, 0);
        tv.setTextColor(R.color.fontcolor);
        tv.setCompoundDrawables(null, drawable, null, null);
        tv.setCompoundDrawablePadding(10);
    }

    /**
     * 取圖片正中間的正方形並縮放
     */
    public static Bitmap centerSquareScaleBitmap(Bitmap bitmap, int edgeLength) {
        if (bitmap == null || edgeLength <= 0) {
            return null;
        }
        Bitmap result = bitmap;
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        if (w >= edgeLength && h >= edgeLength) {
            int longerEdge = (int) (edgeLength * Math.max(w, h) / Math.min(w, h));
            int scaledWidth = w > h ? longerEdge : edgeLength;
            int scaledHeight = w > h ? edgeLength : longerEdge;

            Bitmap scaled;
            try {
                scaled = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
            } catch (Exception e) {
                return null;
            }

            int xTopLeft = (scaledWidth - edgeLength) / 2;
            int yTopLeft = (scaledHeight - edgeLength) / 2;
            try {
                result = Bitmap.createBitmap(scaled, xTopLeft, yTopLeft,
                        edgeLength, edgeLength);
                scaled.recycle();
            } catch (Exception e) {
                return null;
            }
        }
        return result;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.share_weibo_tv:
                break;
            case R.id.share_weixin_tv:
                break;
            case R.id.share_qq_tv:
                break;
            case R.id.share_kongjian_tv:
                break;
            case R.id.cancel_btn:
                finish();
                break;
            default:
                break;
        }
    }
}

步驟四:觸發

在需要的位置呼叫 startActivity(new Intent(this, MyDialogActivity.class)) 即可。

兩種方案怎麼選

AlertDialog 的優點是輕量、API 簡單、自帶遮罩與返回鍵處理;缺點是客製空間受限,要做到複雜排版得硬塞自訂 View。Activity 方案自由度最高,能使用完整的生命週期與 Fragment,代價是必須自己處理「點擊外部是否關閉」、「返回鍵行為」與轉場動畫,並在 Manifest 中正確掛上透明 Dialog 主題。

另外提醒:drawable.setBounds(0, 48, 0, 48) 這類寫法會讓圖示寬高為零,原範例同時呼叫了 setCompoundDrawablesWithIntrinsicBounds 才會正常顯示。建議只保留其中一種設定方式,避免混淆。

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