Android 点击AlertDialog上的确定和取消按钮,使对话框不消失方法

Android中的AlertDialog弹出框在被点击时, 无论点击哪个按钮都会关闭窗口。但是有时候我们不需要它关闭,例如输入用户名和密码,输错了,提示重新输入。那么怎么做到点击确定或者取消按钮不关闭对话框呢?

java代码如下:

 //包含EditText的AlertDialog
 AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
 View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_normal_layout,null);
 EditText et_imei = view.findViewById(R.id.et_imei);
 alertDialog.setTitle("请输入IMEI").setView(view).setNeutralButton("确定", new DialogInterface.OnClickListener() {
     @Override
     public void onClick(DialogInterface dialog, int which) {
     
	 		canCloseDialog(dialogInterface, false);//不关闭对话框
     }
 }).setPositiveButton("取消", new DialogInterface.OnClickListener() {
     @Override
     public void onClick(DialogInterface dialog, int which) {
     
            canCloseDialog(dialogInterface, true);//关闭对话框
     }
 }).create();
 alertDialog.show();

// 关键部分在这里
private void canCloseDialog(DialogInterface dialogInterface, boolean close) {
	try {
		Field field = dialogInterface.getClass().getSuperclass().getDeclaredField("mShowing");

		field.setAccessible(true);

		field.set(dialogInterface, close);

	} catch (Exception e) {
		e.printStackTrace();
	}
}

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:orientation="vertical"
    android:padding="15dp" >

    <EditText
 		android:id="@+id/et_imei"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入IMEI"
        android:maxLength="15"
        android:inputType="number"
        android:maxLines="1"/>

</LinearLayout>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值