Android自定义弹出框AlertDialog

本文介绍了如何在Android中自定义弹出框AlertDialog,通过创建XML布局文件、重写Dialog类以及详细调用过程,展示了完整的自定义步骤,并提供了代码示例链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


今天有空把自定义弹出框研究了一下,一直在用,都没有仔细的看代码,今儿mark一下。

先上个图,做出来的效果:










Step 1: 先自定义一个显示图,

我写的XML文件如下:

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

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/window_bg">

        <TextView
            android:id="@+id/message"
            android:layout_width="150dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="提示信息"
            android:textColor="#333333"
            android:textSize="21dp" />


        <View
            android:layout_width="fill_parent"
            android:layout_height="2dip"
            android:background="#FF909090" />

        <LinearLayout
            android:layout_width="150dp"
            android:layout_height="40dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/negativeButton"
                android:layout_width="70dp"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="取消"
                android:textColor="#333333"
                android:clickable="true"
                android:textSize="18dp" />

            <View
                android:layout_width="2dip"
                android:layout_height="match_parent"
                android:background="#FF909090" />

            <TextView
                android:id="@+id/positiveButton"
                android:layout_width="70dp"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="确定"
                android:clickable="true"
                android:textColor="#333333"
                android:textSize="18dp" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

这里为了让现实框变成圆角的,在linearlayout空间上加了一个background,文件名是window_bg,具体的圆角实现如下:

<?xml version="1.0" encoding="UTF-8"?>
<!-- 顶部带圆角 白色背景 灰色边框 长方体 -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <solid android:color="#FFFFFF" />
            <corners android:topLeftRadius="10dp" android:topRightRadius="10dp"
                android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp" />
            <stroke android:width="1dp" android:color="#ffa8abad" />
        </shape>
    </item>
    <item android:top="1dp" android:left="1dp" android:right="1dp" android:bottom="1dp">
        <shape>
            <solid android:color="#FFFFFF" />
            <corners android:topLeftRadius="10dp" android:topRightRadius="10dp"
                android:bottomRightRadius="10dp" android:bottomLeftRadius="10dp" />
            <stroke android:width="1dp" android:color="#ffffffff" />
        </shape>
    </item>
</layer-list>
这样就完成了显示图的设计,第一步完成。


step 2: 重写Dialog类

这里用了继承,在继承了Dialog类之后,重写所有的方法,同时,在里面加入自己需要的控件处理,请看代码和注释:

package com.example.blyang.myapplication;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;


public class MyDialog extends Dialog {

	public MyDialog(Context context) {
		super(context);
	}

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

	public static class Builder {
		private Context context;
		private String message;   //展示的提示信息
		private String positiveButtonText;  //确定按钮
		private String negativeButtonText;  //取消按钮
		private View contentView;
		private OnClickListener positiveButtonClickListener;  //确定响应监听
		private OnClickListener negativeButtonClickListener;  //取消响应监听


		public Builder(Context context) {
			this.context = context;
		}

		public Builder setMessage(String message) {
			this.message = message;
			return this;
		}

		/**
		 * Set the Dialog message from resource
		 * 
		 * @param
		 * @return
		 */
		public Builder setMessage(int message) {
			this.message = (String) context.getText(message);
			return this;
		}

		/**
		 * Set the Dialog title from resource
		 * 
		 * @param title
		 * @return
		 */
		public Builder setTitle(int title) {
			return this;
		}

		/**
		 * Set the Dialog title from String
		 * 
		 * @param title
		 * @return
		 */

		public Builder setTitle(String title) {
			return this;
		}

		public Builder setContentView(View v) {
			this.contentView = v;
			return this;
		}

		/**
		 * 响应监听器
		 */
		public Builder setPositiveButton(int positiveButtonText,
				OnClickListener listener) {
			this.positiveButtonText = (String) context
					.getText(positiveButtonText);
			this.positiveButtonClickListener = listener;
			return this;
		}

		public Builder setPositiveButton(String positiveButtonText,
				OnClickListener listener) {
			this.positiveButtonText = positiveButtonText;
			this.positiveButtonClickListener = listener;
			return this;
		}

		public Builder setNegativeButton(int negativeButtonText,
				OnClickListener listener) {
			this.negativeButtonText = (String) context
					.getText(negativeButtonText);
			this.negativeButtonClickListener = listener;
			return this;
		}

		public Builder setNegativeButton(String negativeButtonText,
				OnClickListener listener) {
			this.negativeButtonText = negativeButtonText;
			this.negativeButtonClickListener = listener;
			return this;
		}

		/**
		 * 包含相应的layout文件
		 * @return
		 */
		public MyDialog create() {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			// 实例化一个AlertDialog,并且设定这个Dialog的style
			final MyDialog dialog = new MyDialog(context,R.style.Dialog);

			View layout = inflater.inflate(R.layout.dialog, null);
			dialog.addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));


			/**
			 * 确定按钮的监听
			 * 如果在实例化这个dialog的时候,确定按钮不为空,这设置它的显示字符串
			 * 如果确定按钮的监听器不为空,则调用响应的控件,给这个控件的监听器赋值
			 * 相反,如果实例化的时候监听器为空,则让这个控件的visibility设置为GONE
			 */
			if (positiveButtonText != null) {
				((TextView) layout.findViewById(R.id.positiveButton))
						.setText(positiveButtonText);

				if (positiveButtonClickListener != null) {
					((TextView) layout.findViewById(R.id.positiveButton))
							.setOnClickListener(new View.OnClickListener() {
								public void onClick(View v) {
									positiveButtonClickListener.onClick(dialog,
											DialogInterface.BUTTON_POSITIVE);
								}
							});
				}
			} else {
				// if no confirm button just set the visibility to GONE
				layout.findViewById(R.id.positiveButton).setVisibility(
						View.GONE);
			}

			/**
			 * 取消按钮的监听
			 * 参考确认按钮的说明
			 */
			if (negativeButtonText != null) {
				((TextView) layout.findViewById(R.id.negativeButton))
						.setText(negativeButtonText);
				if (negativeButtonClickListener != null) {
					((TextView) layout.findViewById(R.id.negativeButton))
							.setOnClickListener(new View.OnClickListener() {
								public void onClick(View v) {
									negativeButtonClickListener.onClick(dialog,
											DialogInterface.BUTTON_NEGATIVE);
								}
							});
				}
			} else {
				// if no confirm button just set the visibility to GONE
				layout.findViewById(R.id.negativeButton).setVisibility(
						View.GONE);
			}

			/**
			 * 设置展示信息
			 */
			if (message != null) {
				((TextView) layout.findViewById(R.id.message)).setText(message);
			}


			dialog.setContentView(layout);

			//创建完成之后,返回这个dialog
			return dialog;
		}

	}
}

到这里,自定义的过程就完成了。注意到,在create的实例化的时候,给了一个style,这个style是很有用的,它的内部代码如下:

    <style name="Dialog" parent="android:style/Theme.Dialog">
        <!-- 设置整个界面背景透明 -->
        <item name="android:background">#00000000</item>

        <!-- 不允许调用的时候出现模糊,也就是不允许主界面有阴影效果,这个要大家可以试一试设成true和false的区别 -->
        <item name="android:backgroundDimEnabled">false</item>

         <!--窗体无标题 -->
        <item name="android:windowNoTitle">true</item>
        
        <!-- 窗体背景透明 -->
        <item name="android:windowBackground">@android:color/transparent</item>

        <!-- 悬浮-->
        <item name="android:windowIsFloating">true</item>
    </style>

下面就是这个重写的类的调用了。


step 3: 重写的类的调用

调用的时候和一般类的调用方法一致,首先要创建并实例化,再添加需要的处理,请看代码和注释:

                MyDialog.Builder builder = new MyDialog.Builder(MainActivity.this);
                builder.setMessage("提示框");

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //设置具体的确认操作事件
                    }
                });

                builder.setNegativeButton("取消" , new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //设置具体的取消操作事件
                    }
                });

                builder.create().show();

到这里就完成了整个自定义和调用的过程。


附上代码链接:https://github.com/BLYang7/MyDialog.git

或者在CDSDN下载:http://download.youkuaiyun.com/detail/sinat_22013331/9464923




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值