Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

前端 未结 23 2122
-上瘾入骨i
-上瘾入骨i 2020-11-22 00:25

I have an application with three tabs.

Each tab has its own layout .xml file. The main.xml has its own map fragment. It\'s the one that shows up when the application

23条回答
  •  天命终不由人
    2020-11-22 01:25

    The problem is that what you are trying to do shouldn't be done. You shouldn't be inflating fragments inside other fragments. From Android's documentation:

    Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically.

    While you may be able to accomplish the task with the hacks presented here, I highly suggest you don't do it. Its impossible to be sure that these hacks will handle what each new Android OS does when you try to inflate a layout for a fragment containing another fragment.

    The only Android-supported way to add a fragment to another fragment is via a transaction from the child fragment manager.

    Simply change your XML layout into an empty container (add an ID if needed):

    
    
    
    

    Then in the Fragment onViewCreated(View view, @Nullable Bundle savedInstanceState) method:

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        FragmentManager fm = getChildFragmentManager();
        SupportMapFragment mapFragment = (SupportMapFragment) fm.findFragmentByTag("mapFragment");
        if (mapFragment == null) {
            mapFragment = new SupportMapFragment();
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(R.id.mapFragmentContainer, mapFragment, "mapFragment");
            ft.commit();
            fm.executePendingTransactions();
        }
        mapFragment.getMapAsync(callback);
    }
    

提交回复
热议问题