Dialog用的是最简单的AlertDialog.Builder建立的,通过setView(view)实现自定义布局,布局里嵌套了一个自定义的fragment。第一次弹出对话框的时候没有问题,第二次再弹的话就会出现错误信息: Binary XML file line #8: Duplicate id , tag null, or parent id 0xffffffff with another fragment for com.whu.geoname.fragment.ImageFlowFragment。
From stackoverflow: Does the fragment in your layout have an android:id attribute?
I suspect this is because the fragment is instantiated each time your layout is inflated, the first time the ID isn’t being used, but the second time the FragmentManager still thinks your Fragment is alive, so the ID is considered a duplicate.
stackoverflow上提供了三种解决方法: Try removing the android:id attribute from your fragment if it exists, or add a placeholder layout such as a framelayout and use a fragmenttransaction to dynamically add the fragment each time your dialog is created. 第一种方法我测试了没有产生效果,而且就算可以的话你也不能对你的fragment进行操作,所以我选择了第三种,在Builder的OnDismissListener监听中将fragment移除掉。 附上关键代码:
FragmentManager fragmentManager = getSupportFragmentManager(); ImageFlowFragment mImageFlowFragment = (ImageFlowFragment) fragmentManager.findFragmentById(R.id.imagefragment); /* ... */ .setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentById(R.id.imagefragment)).commit(); } });