how to get a fragment added in an XML layout

前端 未结 5 1508
暗喜
暗喜 2020-12-05 12:27

I have a layout which includes a fragment as follows:



        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 13:20

    If the fragment is embedded in another fragment, you need getChildFragmentManager() but not getFragmentManager(). For example, in layout xml define the fragment like this:

    
    

    in Code, you can get the fragment instance like this:

    FragmentManager f = getChildFragmentManager();
    FragmentTransaction transaction = f.beginTransaction();
    chatFragment = f.findFragmentById(R.id.chatfragment);
    
    if (chatFragment != null) {
       transaction.hide(chatFragment);
    }
    transaction.commit();
    

提交回复
热议问题