MainActivity.javaactivity_main.xml
package com.codinginflow.saveinstancestateexample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView mTextViewCount; private int mCount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextViewCount = findViewById(R.id.text_view_count); Button buttonDecrement = findViewById(R.id.button_decrement); Button buttonIncrement = findViewById(R.id.button_increment); buttonDecrement.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { decrement(); } }); buttonIncrement.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { increment(); } }); if (savedInstanceState != null) { mCount = savedInstanceState.getInt("count"); mTextViewCount.setText(String.valueOf(mCount)); } } private void decrement() { mCount--; mTextViewCount.setText(String.valueOf(mCount)); } private void increment() { mCount++; mTextViewCount.setText(String.valueOf(mCount)); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("count", mCount); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="horizontal" tools:context="com.codinginflow.saveinstancestateexample.MainActivity"> <Button android:id="@+id/button_decrement" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="-" /> <TextView android:id="@+id/text_view_count" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:text="0" android:textColor="@android:color/black" android:textSize="50sp" /> <Button android:id="@+id/button_increment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+" /> </LinearLayout>