安卓自定义对话框及The specified child already has a child问题

来源:互联网 发布:java进销存软件源码 编辑:程序博客网 时间:2024/06/07 18:13

问题:在android开发过程中,有时会在不同情况下遇到同种问题:The specified child already has a parent.You must call removeView() on the child's parent first.日志中如下图所示:


分析:意思是这个特定的child已经有一个parent了,如果你要继续使用它,就必须先调用removeView()方法移除它原来的的parent,才能继续你的内容。

举例:在主activity中点击按键弹出自定义View的对话框

首先:

setContentView(R.layout.main); 

etContentView(R.layout.main
其次

其次:对button进行click监听,click函数里调用对话框函数

1.对话框的处理:新建defView,里面有一个edittext(其他控件的也一样)

  <EditText         android:id="@+id/filename"        android:layout_width="match_parent"        android:layout_height="wrap_content"/>

2.因为对话框中要调用的控件不在布局文件main.xml中,所以我们必须先调用布局填充类的相关函数找到该布局

LinearLayout def = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_save_file, null);

3.然后在该布局中找到相应的控件:

edtTxtFileName = (EditText) saveForm.findViewById(R.id.filename);

4.click函数中对话框的建立

AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("保存sdcard/sign/").setIcon(R.drawable.save_file).setView(def);//这里给对话框加入了自定义的内容
</pre><pre name="code" class="java">最后:在对话框本身的按键确定或者取消click响应中加入:
((ViewGroup) saveForm.getParent()).removeView(def);

0 0