Search code examples
androidandroid-fragmentsorientation

Fragment TextView state after orientation change (with different layouts)


I'm trying to create a calculator with a simple version in portrait mode and a scientific version alongside a list of past calculation in landscape. I'm running into the issue of passing the current value in my textview of portrait mode to the landscape mode.

My main activity:

private FragmentManager fm;
Fragment fragmentScientific, fragmentList

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    fm = getSupportFragmentManager();
    setUpFragments();
}
private void setUpFragments() {
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        fragmentScientific= fm.findFragmentById(R.id.container_ui_landscape);
        fragmentList= fm.findFragmentById(R.id.container_list);
        if ((fragmentScientific == null) && (fragmentList == null)) {
            fragmentScientific= new ScientificFragment();
            fragmentList= new RecordListFragment();
            fm.beginTransaction()
                    .add(R.id.container_ui_landscape, fragmentScientific)
                    .add(R.id.container_list, fragmentList)
                    .commit();
        }
    } else {
        fragmentScientific= fm.findFragmentById(R.id.container_ui_portrait);
        if (fragmentScientific== null) {
            fragmentScientific = new ScientificFragment();
            fm.beginTransaction()
                    .add(R.id.container_ui_portrait, fragmentScientific)
                    .commit();
        }
    }
}

I've attempted to use onSaveInstanceState bundle in my ScientificFragment class to carry it

    private TextView newRes;
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putString("currentCal", newRes.getText().toString());
    }

but I just ended up having two separate saved bundles, one for portrait and one for landscape.


Solution

  • The Android system actually handles view restoration for you on an orientation change, regardless of whether you have different layouts. The key is to have identical IDs across both layouts. Using different ones or not specifying anything at all will prevent their state being restored.