我有一个FragmentActivity,其中包含一些片段。当我从片段上走时,我处于将手机处于纵向位置的片段A上,将我在代码setOrientation()中设置为Landscape的下一个片段B片段上,按住时会出现黑屏直到我将手机转到横向时,手机才会以纵向和布局显示在第二个片段上。我的印象是,无论您如何握住手机,当执行setRequestedOrientation()时,它都应强制显示您提供的布局

视觉效果:

-----------         -----------
|         |         |         |                         ---------------
|         |         |         |                         |             |
| Frag A  |   ->    | Frag B  |   -> Until I turn  ->   |   Frag B    |
|         |(then to)| (black) |     it to Landscape     | (not black  |
|         |         |         |                         |   anymore)  |
|         |         |         |                         ---------------
-----------         -----------


码:

保持方向变化的MainActivity:

    // Set Orientation of the Activity.
public void setOrientation(int sensor) {
    if (sensor == 1) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
    } else if (sensor == 2) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
    } else if (sensor == 3) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    } else if (sensor == 4) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    } else if (sensor == 5) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}


FragA:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // Set the orientation to be in portrait and landscape.
    ((MainActivity) getActivity()).setOrientation(1);
    ...
}


FragB:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // Set the orientation to be in landscape.
    ((MainActivity) getActivity()).setOrientation(5);
    ...
}

最佳答案

您必须在onActivityCreated中调用getActivity()

10-08 17:43