Dialog Fragment java.lang.IllegalStateException:指定的子项已经有父项。您必须先调用子对象的父对象的removeView()。

问题描述:

我正在调用从自定义适配器加载的对话框片段中的列表。Dialog Fragment java.lang.IllegalStateException:指定的子项已经有父项。您必须先调用子对象的父对象的removeView()。

加载我的片段

ProfileListViewHolder.imageButtonMore.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      ProfileDialog ProfileDialogFragment = new ProfileDialog(); 

      ProfileDialogFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.CustomDialog); 
      android.support.v4.app.FragmentTransaction fragmentManager =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction(); 

      fragmentManager.replace(R.id.drawer_layout,ProfileDialogFragment) .addToBackStack(null).commit(); 

     } 
    }); 

,这是我的对话,我使用

public class ProfileDialog extends android.support.v4.app.DialogFragment { 

private Context context; 

public View profileView; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
} 


public void setTitle(String title) { 
    Dialog dialog = getDialog(); 
    dialog.setTitle(title); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    if (profileView == null) { 
      profileView = inflater.inflate(R.layout.fragment_profile_dialog, container,false); 
    } else { 
     ((ViewGroup) profileView .getParent()).removeView(profileView); 
    } 

    ListView profileListView = (ListView) profileView.findViewById(R.id.lstvSelectedProfile); 


    return profileListView; 
} 

@Override 
public void onStart() { 
    super.onStart(); 
    //addInnerFragment(); 
} 

@Override 
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 
    super.onViewCreated(view, savedInstanceState); 


} 
@Override 
public Dialog onCreateDialog(Bundle savedInstanceState) { 
    Dialog dialog = super.onCreateDialog(savedInstanceState); 
    return dialog; 
} 

} 
+1

什么目的'((ViewGroup中)profileView.getParent())。removeView(profileView)'? – azizbekian

+0

@azizbekian:我认为这可能会帮助我删除可能在这里困扰的父项 –

+0

如果您想使用'ProfileDialog'作为对话框,则需要使用它的show()方法,而不是使用事务在那里使用。 –

要退回profileListView而不是profileView。改变这样的代码,

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     profileView = inflater.inflate(R.layout.fragment_profile_dialog, container, false); 
     ListView profileListView = (ListView) profileView.findViewById(R.id.lstvSelectedProfile); 
     return profileView; 
    } 

尝试

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    profileView = inflater.inflate(R.layout.fragment_profile_dialog, container,false); 

    ListView profileListView = (ListView) profileView.findViewById(R.id.lstvSelectedProfile); 

    return profileView; 
} 
+0

这与Krish的回答有什么不同? –