0

I have an Adapter class and a MainActivity. The Adapter class displays the list of children names and beside the names, it displays the time they arrived to the school. Problem is when I rotate to landscape, the time values are lost.

I considered adding in my Manifest under MainActivity

android:configChanges="orientation|keyboardHidden|screenSize"

What happens is that the time values are not lost in landscape mode but the look of the layout appears same as that of portrait mode. In real, the landscape layout looks a bit different from portrait layout.

What do I do in this case in order to obtain time values and also maintain the look of the landscape layout.

Mark023
  • 105
  • 12

2 Answers2

4

There are 2 options:

  1. use onSaveInstanceState(Bundle outState) method in your Activity or Fragment - to save your data and restore them after rotation (in onCreate(Bundle savedInstanceState) or onRestoreInstanceState(Bundle savedInstanceState))

Example:

 @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("time_data", (Seriazable) mTimeList);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ...

        if (savedInstanceState != null) {
            // restore value of members from saved state
            mTimeList = savedInstanceState.getSerializable("time_data");
        }

        ...
    }
  1. use android:configChanges as you already use to handle changes by yourself but inflate landscape layout after rotation

Example:

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

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

I prefer the first option and also this proposed in Android guide.

comrade
  • 4,590
  • 5
  • 33
  • 48
  • Thankyou :) if i use second solution of yours, in onConfigurationChanged() under if case, I need to set layout-land xml for the Adapter class. How do I do that – Mark023 Jul 12 '16 at 08:02
  • You can check this StackOverflow [answer](http://stackoverflow.com/a/17050108/1423876) related to layout inflation after config changes. There are some more questions on StackOverflow related to layout inflation so you can check them and use what more applicable for your purpose. – comrade Jul 12 '16 at 08:34
0

you can simply set screen orientation to portrait to your perticular activity so it cant be rotate. (if you want) like this way:

 <activity android:name=".MainActivity"
            android:screenOrientation="portrait">
  </activity>
Sagar Chavada
  • 5,169
  • 7
  • 40
  • 67