Android Fragment no view found for ID?

前端 未结 30 1992
逝去的感伤
逝去的感伤 2020-11-22 05:33

I have a fragment I am trying to add into a view.

FragmentManager fragMgr=getSupportFragmentManager();
feed_parser_activity content = (feed_parser_activity)f         


        
30条回答
  •  逝去的感伤
    2020-11-22 06:13

    I've had the same problem when was doing fragment transaction while activity creation.

    The core problem is what Nick has already pointed out - view tree has not been inflated yet. But his solution didn't work - the same exception in onResume, onPostCreate etc.

    The solution is to add callback to container fragment to signal when it's ready:

    public class MyContainerFragment extends Fragment {
        public static interface Callbacks {
            void onMyContainerAttached();
        }
    
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            Log.d(TAG, "--- onAttach");
            ((Callbacks) activity).onMyContainerAttached();
        }
    
        //... rest of code
    }
    

    And then in activity:

    public class MainActivity extends Activity
            implements MyContainerFragment.Callbacks
    {
        @Override
        public void onMyContainerAttached() {
            getFragmentManager()
                    .beginTransaction()
                    .replace(R.id.containerFrame, new MyFragment())
                    .commit();
        }
    
        //...
    }
    

提交回复
热议问题