Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

android - Allow rotation/landscape in one fragment

My app has a single Activity with a FragmentPagerAdapter with four fragments (Using the ViewPagerIndicator library). One of these fragments has designs for both a separate portrait and landscape layout, the other three do not and need to be fixed to portrait orientation.

My thought was to set android:configChanges="orientation" in the manifest and call getActivity().setRequestedScreenOrientation() in the onResume() of all the fragments, locking to SCREEN_ORIENTATION_PORTRAIT in three of them but to SCREEN_ORIENTATION_UNSPECIFIED in the one that needs to allow rotation, but this doesn't work. The app remains in portrait mode.

Is there a way to achieve this?

It isn't actually necessary for the actual activity to rotate if there is anyway to allow a fragment to change orientation without its activity doing so, but I have not found anything mentioning this being possible. It would also be equally ok if the activity rotates since the tab bar will be hidden when in landscape orientation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...