我在 xml 布局中为我的 fragment 定义一个 ID:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/test_fragment"
...
然后我在activity的onCreate方法中添加这个 fragment :
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment);
fragmentTransaction.commit();
这一切都很好。替换 fragment ,也正在工作。
稍后我尝试在 Activity 的一种方法中通过其 ID 检索此 fragment :
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.test_fragment);
这样做会导致 myFragment 为 null
。总是。
当我尝试对标签而不是 ID 执行相同操作时,我可以通过标签检索 fragment 而不会出现任何问题:
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment, "testfragment");
fragmentTransaction.commit();
...
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag("testfragment");
为什么 findFragmentById 找不到 fragment ,而 findFragmentByTag 却可以?我错过了什么吗?
最佳答案
R.id.test_fragment
不是您的 fragment 的 ID,而是您的 LinearLayout 的 ID
调用 add(int containerViewId, Fragment fragment)
将添加一个不带标签的 fragment 。
因此,或者您使用 add(int containerViewId, Fragment fragment, String tag)
并使用您的标签(作为 ID)取回您的 fragment
关于android - findFragmentById 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10833666/