findFragmentById always returns null

前端 未结 9 612
时光说笑
时光说笑 2020-12-01 17:31

I\'m defining an ID for my fragment in the xml layout:




        
相关标签:
9条回答
  • 2020-12-01 18:25

    I was using android.support.v4.app.Fragment in my layout while calling getFragmentManager() which actually searched for android.app.Fragment subclasses and I got null. So the fix was to call getSupportFragmentManager() instead.

    In general make sure the package of a fragment you are subclassing and using in your layout is the same returned by the corresponding FragmentManager which performs search.

    0 讨论(0)
  • 2020-12-01 18:26

    Or, you should have instead used :

    (MyFragment) getFragmentManager().findFragmentById(R.id.fragment_container);
    
    0 讨论(0)
  • 2020-12-01 18:30

    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)

    0 讨论(0)
提交回复
热议问题