Android 不同碎片的特定方向

Android 不同碎片的特定方向,android,android-fragments,screen-orientation,Android,Android Fragments,Screen Orientation,我想在我的应用程序中独立地更改每个片段的屏幕方向,即片段A仅为横向,片段B仅为纵向,就像我可以使用AndroidManifest.xml为活动更改屏幕方向一样 当我创建片段时,我使用fragment.setArgunents为每个片段传递一个特定的屏幕方向常量 我在基本活动中切换片段,如下所示: public void setCurrentFragment(Fragment fragment, boolean addToBackstack) { FragmentTransacti

我想在我的应用程序中独立地更改每个片段的屏幕方向,即片段A仅为横向,片段B仅为纵向,就像我可以使用AndroidManifest.xml为活动更改屏幕方向一样

当我创建片段时,我使用fragment.setArgunents为每个片段传递一个特定的屏幕方向常量

我在基本活动中切换片段,如下所示:

public void setCurrentFragment(Fragment fragment, boolean addToBackstack) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, fragment);
        if (addToBackstack)
            fragmentTransaction.addToBackStack(Integer.toString(fragmentCount++));
        fragmentTransaction.commit();
}
我已经尝试将方向更改为setCurrentFragment内片段参数中存储的方向,在onResume中,使用setRequestedOrientation创建片段方法时,每个方法都会导致方向更改的无限循环,整个活动被一次又一次地破坏和重新创建


有人知道这样做的正确方法吗?

看起来唯一的方法是将当前方向存储在其他位置,例如作为静态变量,以检查在重新创建活动之前设置的方向,并在每个片段中使用getFragmentManager.getFragments检查它是否是堆栈中的最后一个方向

以下代码对我来说很好,我的getArguments包内容只有几个字符串:

private static int orientation;

@Override
public void onResume() {
super.onResume();
    Fragment lastFragment = getFragmentManager().getFragments().get(getFragmentManager().getFragments().size() - 1);
    if (lastFragment != null && lastFragment.getClass().equals(getClass())) {
        if (lastFragment.getArguments() != null && getArguments() != null) {
            if (lastFragment.getArguments().toString().equals(getArguments().toString())) {
                setCurrentOrientation(fragmentOrientation, getActivity());                  
            }
        }
    } else {
        setCurrentOrientation(contentPage, getActivity());
    }
}

private void setCurrentOrientation(int orientation) {
    if (orientation == currentOrientation) {
        return;
    } else {
        currentOrientation = orientation;
    }
    getActivity().setRequestedOrientation(currentOrientation);
}