How to lock fragment orientation without locking activity orientation?

后端 未结 2 494
长发绾君心
长发绾君心 2021-02-07 08:38

I have a specific use case where I want a fragment to be locked in portrait mode, but still rotate the activity (and/or other fragments visible in the same activity). Is it poss

2条回答
  •  梦毁少年i
    2021-02-07 09:21

    Take a look at this answer:

    Override setUserVisibleHint() in each fragment.

    In the portrait only fragments:

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser) {
            Activity a = getActivity();
            if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
    

    in the the portrait/landscape fragment:

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser) {
            Activity a = getActivity();
            if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
        }
    }
    

    This will allow the whole activity to rotate in one fragment, but fix it to portrait in others.

    Answered by: https://stackoverflow.com/a/13252788/2767703

提交回复
热议问题