findFragmentById总是返回null [英] findFragmentById always returns null
问题描述
我在XML布局定义一个ID为我的片段:
< XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:ID =@ + ID / test_fragment
...
然后,我添加此片段在活动的onCreate方法:
MyFragment myFragment =新MyFragment();
fragmentTransaction.add(R.id.fragment_container,myFragment);
fragmentTransaction.commit();
这是所有工作的罚款。更换碎片和还在。
后来我想检索此片段通过其ID中的活动的方法之一:
MyFragment myFragment =(MyFragment)getFragmentManager()findFragmentById(R.id.test_fragment)。
这样做会导致myFragment是空
。始终。
当我试图用标签来代替标识做同样的我可以检索该片段由它的标签,没有任何问题:
MyFragment myFragment =新MyFragment();
fragmentTransaction.add(R.id.fragment_container,myFragment,testfragment);
fragmentTransaction.commit();
...
MyFragment myFragment =(MyFragment)getFragmentManager()findFragmentByTag(testfragment)。
为什么不能findFragmentById找到片段,但findFragmentByTag这样做?我失去了一些东西?
R.id.test_fragment
不是你片段的ID,但你的LinearLayout <的ID / P>
调用添加(INT containerViewId,片段片段)
将添加一个片段没有标签。
所以,或者你使用添加(INT containerViewId,片段的片段,字符串标签)
键,你会得到使用标记的片段(作为ID)
I'm defining an ID for my fragment in the xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/test_fragment"
...
Then I add this fragment in the activity's onCreate method:
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment);
fragmentTransaction.commit();
This is all working fine. Replacing fragments and is also working.
Later I'm trying to retrieve this fragment by its ID in one of the activity's methods:
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.test_fragment);
Doing so leads to myFragment being null
. Always.
When I try to do the same with tags instead of IDs I can retrieve the fragment by its tag without any problems:
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment, "testfragment");
fragmentTransaction.commit();
...
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag("testfragment");
Why can't findFragmentById find the fragment, but findFragmentByTag does so? Am I missing something?
R.id.test_fragment
is not the ID of your fragment but the id of your LinearLayout
Calling add(int containerViewId, Fragment fragment)
will add a fragment without a tag.
So or you use add(int containerViewId, Fragment fragment, String tag)
and you get back your fragment using your tag (as an ID)
这篇关于findFragmentById总是返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!