0

I need to replace my layout on orientation change and keep my views state and listeners (ex. in portrait mode I change a TextView color from blue to red and when I rotate the device the new layout with the same TextView needs to be red). I have 2 layouts: one in layout/ and one in layout-land/ and I added in AndroidManifest.xml this: android:configChanges="orientation|keyboardHidden|screenSize" and this is my onConfigurationChanged

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    mDisplayWidth = Helper.getDisplayWidth(context);
    mDisplayHeight = Helper.getDisplayHeight(context);
    mDisplayOrientation = getResources().getConfiguration().orientation;

    if(mDisplayOrientation == Configuration.ORIENTATION_LANDSCAPE){
        //landscape

    }else{
        //portret
    }

    final View newView = View.inflate(getActivity(), R.layout.harta, null);
    ViewGroup rootView = (ViewGroup) getView();
    rootView.removeAllViews();
    rootView.addView(newView);
}

The problem is that the new layout doesn't keep the old state and listeners, how can I achieve this?

  • You'll want to use onSaveInstanceState and put the elements you need into a bundle and pull them out in the onCreate from the saved bundle state. When you use layoutLand it redraws the screen and you have to save any elements or data and bring it back when its redrawn. http://developer.android.com/training/basics/activity-lifecycle/recreating.html – aminner May 11 '16 at 13:51
  • I could not find a concrete exemple and i tried the exemple from here http://developer.android.com/training/basics/activity-lifecycle/recreating.html but it's not working, i forgot to mention that i have a fragment with a MapView inside – Lucian Ilie May 11 '16 at 15:11
  • See if this helps http://stackoverflow.com/questions/12214600/save-data-and-change-orientation – aminner May 11 '16 at 15:20

1 Answers1

0

Delete android:configChanges="orientation|keyboardHidden|screenSize" from manifest. Else onConfigurationChanged() doesn't cause;

Nikita G.
  • 720
  • 1
  • 14
  • 22
  • If i do that my activity will be destroyed and recreated, and i need my view to remain the same. – Lucian Ilie May 11 '16 at 15:03
  • If you can't delete configuration from manifest, then you can save state activity in `onSavedInstanceState();` and restore in `onRestoreInstanceState();` – Nikita G. May 11 '16 at 22:13