Android旋转屏幕并替换片段

时间:2017-07-22 16:08:45

标签: android fragment

所以,我有一个主要活动,片段(FragmentA)设置为默认值。

我的工具栏中有两个按钮; 按钮1旋转屏幕并将FragmentA的布局设置为横向 按钮2应该用新的FragmentB替换FragmentA。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.split_screen) {
        currentFragment = new DualScreenFragment();
        toggleSplitScreen();
    }
    else if (id == R.id.rotate_screen) {
        currentFragment = new PrimaryPDFFragment();
        toggleScreenOrientation();
    }

    return super.onOptionsItemSelected(item);
}

toggleSplitScreen():

    private void toggleSplitScreen() {
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.target_pane, currentFragment);
    transaction.commit();
    if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}

toggleScreenOrientation():

    private void toggleScreenOrientation() {
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}

然而,我似乎无法一次性处理替换和旋转。我必须按分屏按钮一次进入横向模式,然后第二次按实际替换片段。

我知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

使用此代码

// Create new fragment and transaction
Fragment newFragment = new BlankFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();