Android findFragmentByTag()返回null
更新: 只是想澄清一下,Android findFragmentByTag()返回null,android,android-fragments,Android,Android Fragments,更新: 只是想澄清一下,show()是一个我没有重写的android.app.DialogFragment方法: public void show(FragmentManager manager, String tag) { mDismissed = false; mShownByMe = true; FragmentTransaction ft = manager.beginTransaction(); ft.add(this, tag); ft.com
show()
是一个我没有重写的android.app.DialogFragment
方法:
public void show(FragmentManager manager, String tag) {
mDismissed = false;
mShownByMe = true;
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commit();
}
我们称之为以下内容,其中MyDialog
扩展了DialogFragment
:
MyDialog dialog = new MyDialog();
dialog.show(getFragmentManager(), MyDialog.TAG);
Fragment f = getFragmentManager().findFragmentByTag(MyDialog.TAG);
但是
f
总是null
。为什么?FindFragmentByTag在找到时返回片段,否则返回null。FindFragmentByTag在找到时返回片段,否则返回null。添加带有片段的标记
Fragment fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
.replace(R.id.container,f,MyDialog.TAG)
.commit();
并且得到
Fragment f = getFragmentManager().findFragmentByTag(MyDialog.TAG);
添加带有片段的标记
Fragment fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
.replace(R.id.container,f,MyDialog.TAG)
.commit();
并且得到
Fragment f = getFragmentManager().findFragmentByTag(MyDialog.TAG);
问题很简单,
DialogFragment.show
使用异步运行的FragmentTransaction.commit
。所以它只会在主线程的下一次迭代中出现。要解决这个问题,只需将这一行添加到代码中
MyDialog dialog = new MyDialog();
dialog.show(getFragmentManager(), MyDialog.TAG);
// Run this line before trying to search for the fragment.
getFragmentManager().executePendingTransactions();
Fragment f = getFragmentManager().findFragmentByTag(MyDialog.TAG);
问题很简单,
DialogFragment.show
使用异步运行的FragmentTransaction.commit
。所以它只会在主线程的下一次迭代中出现。要解决这个问题,只需将这一行添加到代码中
MyDialog dialog = new MyDialog();
dialog.show(getFragmentManager(), MyDialog.TAG);
// Run this line before trying to search for the fragment.
getFragmentManager().executePendingTransactions();
Fragment f = getFragmentManager().findFragmentByTag(MyDialog.TAG);
您是否使用相同的标记设置了fragment?请在MyDialog类中的show()方法上发布代码。@hr据我所知,fragmentManager会将标记与片段关联,正如我现在添加的代码所示。当您使用FragmentTransition添加片段时,您可以设置片段的tab…如果您没有设置它,则无法获得它的可能副本。您是否使用相同的标记设置了片段?请在MyDialog类中发布show()方法上的代码。@HRaval据我所知,标签通过fragmentManager与片段关联,正如我现在添加的代码所示。当您使用FragmentTransition添加它时,您可以设置片段的tab…如果您没有设置它,那么您将无法获得可能的重复。问题是为什么它找不到最近添加的片段。当然。问题是为什么它找不到最近添加的片段。你能解释一下这与
show()
的不同之处吗?也就是说,replace()
如何比add()
更好访问此页面您能解释一下这与show()
有什么不同吗?也就是说,replace()