Android通用弹出框Dialog工具类

应用开发中一般都会将Dialog做成统一风格,基本上包含Title、Message、Button(单/双)三部分,大多数情况下都是对这三部分的不同组合,比如Message+Button(单/双)、Title+Button(单/双)、Message,个人针对这个需求做了个通用的工具类PopupDialog,方便使用,这里共享给有需要的童鞋:

预览图:





PopupDialog.java:

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.reflect.Method;

/**
 * Created by weishj on 2018/1/11.
 */
public class PopupDialog extends AlertDialog {
	private static final String TAG = "PopupDialog";
	private View view;
	private Context context;
	private TextView title;
	private ImageView close;
	private TextView msg;
	private TextView confirm;
	private TextView cancel;
	private LinearLayout bottomLl;
	private RelativeLayout topRl;
	private View verticalLine;
	private int width;

	protected PopupDialog(Context context, boolean cancelable, boolean canceledOnTouchOutside) {
		super(context, R.style.Dialog_Common);
		this.context = context;
		double deviceWidth = getScreenWidth(this.context);
		width = (int) (deviceWidth * 0.7);
		setCancelable(cancelable);
		setCanceledOnTouchOutside(canceledOnTouchOutside);
		LayoutInflater inflater = LayoutInflater.from(this.context);
		view = inflater.inflate(R.layout.popup_dialog, null);
		initView();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams
				.WRAP_CONTENT, 0);
		setContentView(view, params);
	}

	public void setDialogTitle(CharSequence title, boolean closeBtn) {
		if (title == null || "".equals(title)) {
			if (this.title != null) {
				this.title.setVisibility(View.GONE);
			}
		} else {
			if (this.title != null) {
				this.title.setText(title);
			}
		}
		if (closeBtn && this.close != null) {
			this.close.setVisibility(View.VISIBLE);
		}
	}

	public void setDialogMessage(CharSequence msg) {
		if (msg == null || "".equals(msg)) {
			if (this.msg != null) {
				this.msg.setVisibility(View.GONE);
			}
		} else {
			if (this.msg != null) {
				this.msg.setText(msg);
			}
		}
	}

	protected void setDialogButton(int whichButton, CharSequence text, final View.OnClickListener listener) {
		if (text == null || "".equals(text)) {
			switch (whichButton) {
				case DialogInterface.BUTTON_POSITIVE: {
					if (this.confirm != null) {
						this.confirm.setVisibility(View.GONE);
					}
					break;
				}
				case DialogInterface.BUTTON_NEGATIVE: {
					if (this.cancel != null) {
						this.cancel.setVisibility(View.GONE);
					}
					break;
				}
				default: {
					Log.e(TAG, "Button can not be found. whichButton=" + whichButton);
				}
			}
		} else {
			switch (whichButton) {
				case DialogInterface.BUTTON_POSITIVE: {
					if (this.confirm != null) {
						this.confirm.setText(text);
						this.confirm.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								if (listener != null) {
									listener.onClick(v);
								}
								dismiss();
							}
						});
					}
					break;
				}
				case DialogInterface.BUTTON_NEGATIVE: {
					if (this.cancel != null) {
						this.cancel.setText(text);
						this.cancel.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								if (listener != null) {
									listener.onClick(v);
								}
								dismiss();
							}
						});
					}
					break;
				}
				default: {
					Log.e(TAG, "Button can not be found. whichButton=" + whichButton);
				}
			}
		}
	}

	public void setDialogButton(String confirm, View.OnClickListener positiveClickListener, String cancel, View
			.OnClickListener negativeClickListener) {
		if ((confirm == null || "".equals(confirm)) && (cancel == null || "".equals(cancel))) {
			if (this.bottomLl != null) {
				this.bottomLl.setVisibility(View.GONE);
			}
		} else if ((confirm != null && !"".equals(confirm)) && (cancel != null && !"".equals(cancel))) {
			setDialogButton(DialogInterface.BUTTON_POSITIVE, confirm, positiveClickListener);
			setDialogButton(DialogInterface.BUTTON_NEGATIVE, cancel, negativeClickListener);
		} else {
			// Hide vertical line
			this.verticalLine.setVisibility(View.GONE);
			// Hide positive button
			setDialogButton(DialogInterface.BUTTON_POSITIVE, null, null);
			if (confirm == null || "".equals(confirm)) {
				setDialogButton(DialogInterface.BUTTON_NEGATIVE, cancel, negativeClickListener);
			} else {
				// confirm is not null and cancel is null
				setDialogButton(DialogInterface.BUTTON_NEGATIVE, confirm, positiveClickListener);
			}

		}
	}

	private void initView() {
		this.title = (TextView) view.findViewById(R.id.common_dialog_title_tv);
		this.close = (ImageView) view.findViewById(R.id.common_dialog_close_iv);
		this.msg = (TextView) view.findViewById(R.id.common_dialog_message_tv);
		// Set Scrollable
		this.msg.setMovementMethod(ScrollingMovementMethod.getInstance());
		this.confirm = (TextView) view.findViewById(R.id.common_dialog_confirm_tv);
		this.cancel = (TextView) view.findViewById(R.id.common_dialog_cancel_tv);
		this.bottomLl = (LinearLayout) view.findViewById(R.id.common_dialog_bottom_ll);
		this.topRl = (RelativeLayout) view.findViewById(R.id.common_dialog_top_rl);
		this.verticalLine = view.findViewById(R.id.common_dialog_vertical_line);

		if (this.close != null) {
			this.close.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dismiss();
				}
			});
		}
	}

	/**
	 * Obtain a confirm dialog instance
	 *
	 * @param context                context
	 * @param title                  title of the dialog, pass null or "" if no title is needed
	 * @param message                message to show
	 * @param confirm                name of confirm button, pass null or "" if no confirm button is needed
	 * @param positiveClickListener  click listener of confirm button
	 * @param cancel                 name of cancel button, pass null or "" if no confirm button is needed
	 * @param negativeClickListener  click listener of cancel button
	 * @param cancelable             cancelable when press back
	 * @param canceledOnTouchOutside canceled on touch outside
	 * @param closeBtn               whether to show close button
	 *
	 * @return PopupDialog
	 */
	public static PopupDialog create(Context context, String title, String message, String confirm, View.OnClickListener
			positiveClickListener, String cancel, View.OnClickListener negativeClickListener, boolean cancelable,
									 boolean canceledOnTouchOutside, boolean closeBtn) {
		PopupDialog dialog = new PopupDialog(context, cancelable, canceledOnTouchOutside);
		dialog.setDialogTitle(title, closeBtn);
		dialog.setDialogMessage(message);
		dialog.setDialogButton(confirm, positiveClickListener, cancel, negativeClickListener);

		return dialog;
	}

	/**
	 * Obtain a confirm dialog instance
	 *
	 * @param context                context
	 * @param titleRes               resource id of the dialog's title, pass 0 if no title is needed
	 * @param messageRes             resource id of the dialog's message, pass 0 if no title is needed
	 * @param confirmRes             resource id of the dialog's confirm button, pass 0 if no title is needed
	 * @param positiveClickListener  click listener of confirm button
	 * @param cancelRes              resource id of the dialog's cancel button, pass 0 if no title is needed
	 * @param negativeClickListener  click listener of cancel button
	 * @param cancelable             cancelable when press back
	 * @param canceledOnTouchOutside canceled on touch outside
	 * @param closeBtn               whether to show close button
	 *
	 * @return PopupDialog
	 */
	public static PopupDialog create(Context context, int titleRes, int messageRes, int confirmRes, View.OnClickListener
			positiveClickListener, int cancelRes, View.OnClickListener negativeClickListener, boolean cancelable,
								  boolean canceledOnTouchOutside, boolean closeBtn) {
		return create(context, titleRes, messageRes, confirmRes, positiveClickListener, cancelRes, negativeClickListener,
				cancelable, canceledOnTouchOutside, closeBtn, null);
	}

	public static PopupDialog create(Context context, int titleRes, int messageRes, int confirmRes, View.OnClickListener
			positiveClickListener, int cancelRes, View.OnClickListener negativeClickListener, boolean cancelable,
								  boolean canceledOnTouchOutside, boolean closeBtn, OnDismissListener listener) {
		PopupDialog dialog = new PopupDialog(context, cancelable, canceledOnTouchOutside);
		if (listener != null) {
			dialog.setOnDismissListener(listener);
		}
		String title = null;
		try {
			title = titleRes > 0 ? context.getResources().getString(titleRes) : null;
		} catch (Resources.NotFoundException e) {
			Log.w(TAG, "Resource not found. resId=" + titleRes, e);
		}
		dialog.setDialogTitle(title, closeBtn);
		String msg = null;
		try {
			msg = messageRes > 0 ? context.getResources().getString(messageRes) : null;
		} catch (Resources.NotFoundException e) {
			Log.w(TAG, "Resource not found. resId=" + messageRes, e);
		}
		dialog.setDialogMessage(msg);
		String confirm = null;
		String cancel = null;
		try {
			confirm = confirmRes > 0 ? context.getResources().getString(confirmRes) : null;
			cancel = cancelRes > 0 ? context.getResources().getString(cancelRes) : null;
		} catch (Resources.NotFoundException e) {
			Log.w(TAG, "Resource not found.", e);
		}
		dialog.setDialogButton(confirm, positiveClickListener, cancel, negativeClickListener);
		
		return dialog;
	}

	public void setCancel(int cancelRes) {
		cancel.setText(context.getResources().getString(cancelRes));
	}

	private int getScreenWidth(Context context) {
		return getScreenSize(context)[0];
	}

	private int getScreenHeight(Context context) {
		return getScreenSize(context)[1];
	}

	private int[] getScreenSize(Context context) {
		WindowManager windowManager;
		try {
			windowManager = (WindowManager)context.getSystemService("window");
		} catch (Throwable var6) {
			Log.w(TAG, var6);
			windowManager = null;
		}

		if(windowManager == null) {
			return new int[]{0, 0};
		} else {
			Display display = windowManager.getDefaultDisplay();
			if(Build.VERSION.SDK_INT < 13) {
				DisplayMetrics t1 = new DisplayMetrics();
				display.getMetrics(t1);
				return new int[]{t1.widthPixels, t1.heightPixels};
			} else {
				try {
					Point t = new Point();
					Method method = display.getClass().getMethod("getRealSize", new Class[]{Point.class});
					method.setAccessible(true);
					method.invoke(display, new Object[]{t});
					return new int[]{t.x, t.y};
				} catch (Throwable var5) {
					Log.w(TAG, var5);
					return new int[]{0, 0};
				}
			}
		}
	}
}

styles.xml:

	<!-- popup dialog -->
	<style name="Dialog_Common" parent="@android:style/Theme.Dialog">
		<!-- 边框 -->
		<item name="android:windowFrame">@null</item>
		<!-- 是否浮现在activity之上 -->
		<item name="android:windowIsFloating">true</item>
		<!-- 半透明 -->
		<item name="android:windowIsTranslucent">false</item>
		<!-- 无标题 -->
		<item name="android:windowNoTitle">true</item>
		<item name="android:windowBackground">@android:color/transparent</item>
		<!-- 自己想要的背景 -->
		<item name="android:background">@android:color/transparent</item>
		<!-- 模糊 -->
		<item name="android:backgroundDimEnabled">true</item>
	</style>

popup_dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
			  xmlns:tools="http://schemas.android.com/tools"
			  android:orientation="vertical"
			  android:layout_width="match_parent"
			  android:layout_height="wrap_content"
			  android:background="@drawable/popup_dialog_bg">
	<RelativeLayout
		android:id="@+id/common_dialog_top_rl"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:paddingLeft="15dp"
		android:paddingRight="15dp"
		android:layout_marginBottom="24dp"
		android:gravity="center_vertical">
		<TextView
			android:id="@+id/common_dialog_title_tv"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:gravity="center_horizontal"
			android:layout_marginTop="20dp"
			android:textSize="18dp"
			android:textColor="#555555"
			tools:text="标题"/>
		<ImageView
			android:id="@+id/common_dialog_close_iv"
			android:layout_width="20dp"
			android:layout_height="20dp"
			android:layout_marginTop="15dp"
			android:layout_alignParentRight="true"
			android:src="@drawable/ic_popup_dialog_close"
			android:visibility="gone"/>
	</RelativeLayout>
	<TextView
		android:id="@+id/common_dialog_message_tv"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:gravity="center"
		android:layout_marginLeft="15dp"
		android:layout_marginRight="15dp"
		android:layout_marginBottom="17dp"
		android:maxLines="5"
		android:minHeight="25dp"
		android:textSize="14dp"
		android:textColor="#555555"
		tools:text="信息"/>
	<View
		android:layout_width="match_parent"
		android:layout_height="1dp"
		android:background="#F5F5F5"/>
	<LinearLayout
		android:id="@+id/common_dialog_bottom_ll"
		android:layout_width="match_parent"
		android:layout_height="50dp"
		android:orientation="horizontal">
		<TextView
			android:id="@+id/common_dialog_cancel_tv"
			android:layout_width="0dp"
			android:layout_height="match_parent"
			android:layout_weight="1"
			android:gravity="center"
			android:clickable="true"
			android:textColor="#0679FE"
			android:textSize="18dp"
			tools:text="取消"/>
		<View
			android:id="@+id/common_dialog_vertical_line"
			android:layout_width="1dp"
			android:layout_height="match_parent"
			android:background="#F5F5F5"/>
		<TextView
			android:id="@+id/common_dialog_confirm_tv"
			android:layout_width="0dp"
			android:layout_height="match_parent"
			android:layout_weight="1"
			android:gravity="center"
			android:clickable="true"
			android:textColor="#0679FE"
			android:textSize="18dp"
			tools:text="确定"/>
	</LinearLayout>
</LinearLayout>

popup_dialog_bg.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
	<corners android:radius="8dp"/>
	<solid android:color="#FFFFFF"/>
	<stroke
		android:width="1px"
		android:color="#2E000000"/>
</shape>

ic_popup_dialog_close.png:


使用方法:

PopupDialog.create(...).show();
点击按钮时会自动关闭dialog
  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论
要在Android应用中弹出全局对话,你可以使用系统提供的WindowManager来实现。下面是一个简单的示例代码: ```java public class GlobalDialog { private WindowManager windowManager; private Context context; private View dialogView; public GlobalDialog(Context context) { this.context = context; } public void showDialog() { // 初始化对话布局 dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_layout, null); // 设置对话的宽高 WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT; layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; // 设置窗口型为全局对话 layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; // 获取WindowManager实例 windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // 将对话添加到WindowManager中 windowManager.addView(dialogView, layoutParams); } public void dismissDialog() { if (windowManager != null && dialogView != null) { windowManager.removeView(dialogView); windowManager = null; dialogView = null; } } } ``` 在上述代码中,我们创建了一个`GlobalDialog`来管理全局对话。通过调用`showDialog()`方法,我们可以在应用中弹出全局对话,而调用`dismissDialog()`方法则可以关闭对话。 在布局文件`dialog_layout.xml`中,你可以自定义对话的样式和内容。 请注意,要使用全局对话,你的应用必须拥有`SYSTEM_ALERT_WINDOW`权限。你可以在AndroidManifest.xml文件中添加以下权限声明: ```xml <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> ``` 同时,从Android 6.0(API级别23)开始,你还需要在运行时请求该权限。 希望这个例子对你有所帮助!如有任何问题,请随时提问。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

未子涵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值