fragments and onConfigurationChanged

前端 未结 5 759
清歌不尽
清歌不尽 2021-02-06 07:00

I\'m trying to do something I do with activities, but within a fragment. What I do is using activities:

First stop the activity restarts when rotating the device a

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 07:42

    If I understand correctly, you don't want to the fragment to reload on each rotation. Instead you want to relayout the views and update them with information you already have.

    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    
        // Get a layout inflater (inflater from getActivity() or getSupportActivity() works as well)
        LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View newView = inflater.inflate(R.layout.frg.myFragment, null);
        // This just inflates the view but doesn't add it to any thing.
        // You need to add it to the root view of the fragment
        ViewGroup rootView = (ViewGroup) getView();
        // Remove all the existing views from the root view.
        // This is also a good place to recycle any resources you won't need anymore
        rootView.removeAllViews();
        rootView.addView(newView);
        // Viola, you have the new view setup
    }
    

    According to the documentation (getView()), getView() returns the same view that you returned from your onCreateView() but it does not. It actually return the parent of the view you returned in onCreateView() which is exactly what you need. getView() will return an instance of NoSaveStateFrameLayout, which is used specifically for Fragments as its root view.

    Hope this helps.

提交回复
热议问题