How to lock fragment orientation without locking activity orientation?

落爺英雄遲暮 提交于 2019-12-03 16:36:56

问题


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 possible to do that?

All the solutions to locking a fragment orientation suggest to use setRequestedOrientation and lock the activity orientation, but I need other visible fragments to rotate.

My app supports API 10+ (if there is a nice solution that uses API 11+ I may consider removing support for landscape in API <11).

Thanks in advance.


回答1:


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




回答2:


Its may be little late for the reply, but as i can see you haven't found a solution, You can try doing this, Whenever you are calling your fragment from your activity, add below code before it

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);

and for all other/default Fragment

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

Hope i helped



来源:https://stackoverflow.com/questions/20370636/how-to-lock-fragment-orientation-without-locking-activity-orientation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!