我定义我的XML布局片段的ID:findFragmentById始终返回null
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/test_fragment"
...
然后我加入这个片段在活动的onCreate方法:
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment);
fragmentTransaction.commit();
这是所有工作精细。替换碎片并且也在工作。
后来我试图找回它的ID这个片段的活性的方法之一:
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentById(R.id.test_fragment);
这样做会导致myFragment是null
。总是。
当我尝试做相同的标签,而不是我的ID可以检索其标签片段,没有任何问题:
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment, "testfragment");
fragmentTransaction.commit();
...
MyFragment myFragment = (MyFragment) getFragmentManager().findFragmentByTag("testfragment");
为什么不能findFragmentById找到片段,但findFragmentByTag是这样做的?我错过了什么吗?
尝试'(MyFragment)getFragmentManager()。findFragmentById(R.id.container);' – offset