软件编程
位置:首页>> 软件编程>> Android编程>> Android中AlertDialog 点击按钮后不关闭对话框的功能

Android中AlertDialog 点击按钮后不关闭对话框的功能

作者:SoftXJ  发布时间:2023-08-04 22:55:50 

标签:alertdialog,Android

Android中AlertDialog 点击按钮后不关闭对话框的功能

这里的问题:当我点击确定按钮,也就是 AlertDialog 里的 PositiveButton 的时候,我们需要判断用户是输入是否符合我们的预期,如果不符合通常提示用户重写输入,且不关闭当前的对话框,但上图中点击按钮后会自动的关闭窗口。

先看原来的这个是怎么写的:


private void openDialog() {
LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.change_password_dialog, null);
final EditText originPasswordEt = (EditText) linearLayout.findViewById(R.id.origin_password);
TextView forgetPassword = (TextView) linearLayout.findViewById(R.id.forget_password);

final AlertDialog dialog = new AlertDialog.Builder(getContext())
 .setView(linearLayout)
 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
  @Override
   public void onClick(DialogInterface dialog, int which) {
   String originPassword = originPasswordEt.getText().toString().trim();
    //传到后台
   }
 })
 .create();

dialog.show();
}

虽然图片里和代码的并不是同一个,但问题是一样的

setPositiveButton 方法中,即使我们没有调用 dialog.dismiss()

但对话框还是会自动的关闭,就算我们在 onClick 里判断输入的内容,错误的提示也会在窗口关闭后才出现。

在 AlertDialog 提供的 API 中我也没有找到可以设置的地方,如果有还请告知。而我解决这个问题的办法:


final AlertDialog dialog = new AlertDialog.Builder(getActivity())
 .setTitle(msg)
 .setView(layout)
 .setNegativeButton("取消", new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialog, int which) {
   dialog.dismiss();
  }
 })
 .setPositiveButton("submit",null)
 .setCancelable(true)
 .create();
dialog.show();

//为了避免点击 positive 按钮后直接关闭 dialog,把点击事件拿出来设置
dialog.getButton(AlertDialog.BUTTON_POSITIVE)
 .setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
 Pattern pattern = Pattern.compile("[0-9]*");
 Matcher matcher = pattern.matcher(editText.getText());
 if (!matcher.matches()){
  showToast("请输入正确的 ID");
  break;
 }
 dialog.dismiss();
 }
}
});

setPositiveButton("submit",null) 监听事件传入 null

在调用 dialog.show() 后再设置 Button 的点击事件,否则 getButton() 会返回空

这样在我们手动调用 dialog.dismiss() 之前,对话框是不会关闭的。

来源:http://www.jianshu.com/p/2278c0b90f0d

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com