您的位置:首页 > 移动开发 > Android开发

Monitor项目开发走过的路~自定义AlertDialog,设置子view

2017-12-03 23:45 465 查看
  AlertDialog是Android开发中经常用到的一个控件,可以很方便地与客户进行交互。一般情况都是弹出一个提示框,然后通过setPositiveButton和setNegativeButton来定义相应的响应事件。可是有时候你可能不仅仅满足于只弹出一个消息提示框来选择确认与否。你可能会想要弹出一个能获取用户输入信息的AlertDialog或者其他更为复杂的界面,当然这是可以实现的。你可以自定义你想要的弹出Dialog的布局界面,然后通过AlertDialog.Builder.setView()方法传入即可。下面是Monitor项目中的一个自定义AlertDialog。

private View dialogView;
private AlertDialog.Builder dialog;

LayoutInflater inflater = getActivity().getLayoutInflater();
dialogView = inflater.inflate(R.layout.file_fragment_edit, null);
dialog = new AlertDialog.Builder(getActivity());
dialog.setTitle("权限获取");
dialog.setMessage("请输入密码,进入超级用户状态");
dialog.setView(dialogView);
dialog.setCancelable(false);

dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//这里定义确认响应事件
Toast.makeText(getActivity(), "您的密码错误!", Toast.LENGTH_SHORT).show();
}
});

dialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//这里定义否定响应事件
}
});


  下面是file_fragment_edit.xml布局文件

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

<EditText
android:id="@+id/editText"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:inputType="textPassword"
android:layout_height="wrap_content"/>

</LinearLayout>


  最后的效果如下,实现了一个可以让用户输入数据的AlertDialog.



  看起来效果还不错,达到了我想要的效果,当我点击Dialog上的按钮之后,没有出现异常,Dialog正常的关闭了,但是紧接着再次点击启动Dialog时就出现了下面的异常。



  很明显这个就是我们在Dialog中自定义View带来的问题,从异常的字面意思,再结合查的资料得知,我的dialogView是通过setView()方法设置为了AlertDialog的子View,当我第一次关闭之后dialogView仍然是之前创建的AlertDialog的子view,所以第二次打开的时候,因为是通过

dialog = new AlertDialog.Builder(getActivity());来创建的一个新的AlertDialog,此时再调用dialog.setView(dialogView);时就抛出了上面的异常,解决这个问题的方法就是在每次关闭AlertDialog时都将dialogView从它的父View中去除掉即可。记得一定是所有关闭Diolog的情况都要去除dialogView.方法如下,在各个按钮的点击事件中增加去除子View的代码

dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//这里定义确认响应事件
((ViewGroup) dialogView.getParent()).removeView(dialogView);//去除子View
Toast.makeText(getActivity(), "您的密码错误!", Toast.LENGTH_SHORT).show();
}
});

dialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//这里定义否定响应事件
((ViewGroup) dialogView.getParent()).removeView(dialogView);//去除子View
}
});


  这样设置后便可以正常运行了,在项目中的文件选择页面也同样用了类似的自定义AlertDialog,这个弹出的界面是我设计的用来选择文件操作目标路径的。同样在所有关闭AlertDialog的情况之前要先去除掉其子View.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐