To Examples

ClickCounter Example

Goal:

Directions:

  1. Create an Android Studio project with name ClickCounter and package it372.clickcounter.
  2. Change the layout to LinearLayout.
  3. Set the layout width and height to "match_parent".
  4. Set orientation to "vertical".
  5. Set the padding to "30dp".
  6. Set the gravity to "center".
  7. Add a text view and two buttons to the linear layout with these attributes:

    Attribute TextView Button Button
    id num_clicks    
    text 0 Click Me Reset
    layout_width wrap-content wrap-content wrap-content
    layout_height wrap-content wrap-content wrap-content
    layout_margin 30dp 30dp 30dp
    layout_gravity center center center
    textAllCaps   false false
    textSize 100dp 25dp 25dp
    onClick   incrementCount resetCount
  8. Run the app to test the layout.  Here are the layout and resource files:
        activity-main.xml
  9. Add the event handlers incrementCount and resetCount to the Java activity file. Here is the resulting file.
        MainActivity.java
  10. Run the app to verify that each click of the Click Me button adds one to the value in the text view and that clicking the Reset button sets the value in the text view to 0.
  11. Rotate the emulator 90 degrees. The layout changes from portrait to landscape and the count changes back to its initial value of 0. If the layout does not change to landscape, go to settings on the emulator, then go to Display and turn on autorotate.
  12. Now run the app again. The layout rotates when the emulator is rotated and the app resets the click count to zero because the app closes and restarts when the emulator is rotated. We need to save the click count when the app closes and restore it when the app restarts.
  13. Add these lines to the end of the onCreate event listener in the Java activity code:
     txtCount = findViewById(R.id.txt_num_clicks);
    if (savedInstanceState != null) {
        count = savedInstanceState.getInt("clickCount");
    }
    else {
        count = 0;
    }
    txtCount.setText(String.valueOf(count));
    
  14. Add this onSaveInstanceState event listener in the Java activity code:
     @Override
    public void onSaveInstanceState(Bundle savedInstanceState)
    {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putInt("clickCount", count);
    }
    
  15. Run the app again. Now the click count is restored from the savedInstanceState object when the emulator is rotated.
  16. Here is the updated Java activity code:
        MainActivity.java