Search code examples
androidchronometer

How to contain value of android chronometer with change in orientation


I am building a simple timer app in which I am using android chronometer to track time passed. but when I start chronometer and change orientation to landscape the chronometer resets and and show 00:00 again. I want it to retain its value. layouts for portrait and landscape are different

portrait--> Layout folder

landscape->layout_land folder

<Chronometer 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content"
    android:id="@+id/chronometer1"
    android:layout_above="@+id/button2"
    android:textStyle="bold"
    android:textColor="@color/Indigo"
    android:text="Chronometer"
    android:layout_toLeftOf="@+id/save_btn"
    android:typeface="serif"
    android:textSize="40dp"/>

Solution

  • Here is what the doc said :

    Recreating an Activity

    Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).

    If you need to Save activity's state before changing orientation, you have to override onSaveInstanceState(). This method will help you save all the values you want to get back after orientation changes. Then restore them in onCreate() method.

    Here is an exemple :

    String myVar;
    
    /* 
         ...
    */
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save myVar's value in saveInstanceState bundle
        savedInstanceState.putString("myVar", myVar);
        super.onSaveInstanceState(savedInstanceState);
    }
    

    Now retrieve it when creating the activity :

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        // savedInstanceState is the bundle in which we stored myVar in onSaveInstanceState() method above
        // savedInstanceState == null means that activity is being created a first time
        if (savedInstanceState == null) {
            // some code here
            myVar = "first value";
        } else {  // savedInstance != null means that activity is being recreated and onSaveInstanceState() has already been called.
            myVar = savedInstanceState.getString("myVar");
        }
        /*
           ...
        */
    }