How to prevent custom views from losing state across screen orientation changes ?


Introduction

Many times in android applications we can get to see when the user changes the screen orientation of the device from portrait to landscape. In that case we can get to see that some of the views within the application loses its state. For example when a user enters any data in a text file and then changes the screen orientation from portrait to landscape, in that case the data which is already entered gets cleared up. To prevent this we have to store the state of that view. In this article we will take a look on How to prevent custom views from losing the state across orientation changes in Android ?

Implementation

We will be creating a simple application in which we will be displaying a text view which is used to display the heading of our application. After that we will be creating an edit text which is used to get the data from the user and a button which is use to display the toast message. Now we will move towards android studio for creating a new project in Android Studio.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note : Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 2 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">
   <!-- on below line creating a text view for heading -->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:layout_margin="10dp"
       android:padding="4dp"
       android:text="Prevent Custom Views from loosing state across screen orientation changes in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp"
       android:textStyle="bold" />
   <!-- on below line creating a text view for displaying a response message -->
   <EditText
       android:id="@+id/idEdtMsg"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_margin="10dp"
       android:hint="Enter your name" />
   <!-- on below line creating a button -->
   <Button
       android:id="@+id/idBtnDisplayToast"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtMsg"
       android:layout_margin="10dp"
       android:text="Display Toast Message"
       android:textAllCaps="false" />
</RelativeLayout>

Explanation : In the above code we are creating a root layout as a Relative Layout. Inside this layout we are creating a text view which is used to display the heading of our application. After that we are creating an edit text in which the user can add his name to display in a toast message. After that we are creating a button to display a toast message. At last we are adding a closing tag for our Relative layout.

Step 3 : Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
   // creating variables for text view on below line.
   private EditText msgEdt;
   private Button displayToastBtn;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       //initializing variable for text view and button on below line.
       msgEdt = findViewById(R.id.idEdtMsg);
       displayToastBtn = findViewById(R.id.idBtnDisplayToast);
       // on below line checking if the saved state is not null.
       if (savedInstanceState != null) {
           // on below line setting the data from the saved state to our edit text.
           msgEdt.setText(savedInstanceState.getString("message"));
       }
       // on below line adding click listner for our button.
       displayToastBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // on below line displaying a toast message.
               Toast.makeText(MainActivity.this, "Hello " + msgEdt.getText().toString(), Toast.LENGTH_SHORT).show();
           }
       });
   }
   // on below line creating a method to saved the instance state.
   @Override
   public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
       super.onSaveInstanceState(outState, outPersistentState);
       // on below line setting outstate to set put the data.
       outState.putString("message", msgEdt.getText().toString());
   }
}

Explanation : In the above code firstly we are creating variables for our edit text and a button. Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file. Inside the onCreate method we are initializing the edit text and out button variables with the id which we have given in our activity_main.xml file.

After that we are checking if the saved instance state is not null. If it is not null then we are getting the data stored in the saved instance state and setting that data in our edit text. After that we are adding an onclick listener for our button. Inside the onclick method we are displaying a toast message with the data from our edit text. Then we are creating one more method named as on saved instance state. Inside this method we are saving the state of the edit text by setting the data from edit text with a key named as message. We will be using that same key to read the data in our onCreate method.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note : Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above article we have taken a look on How to prevent the custom views from losing state across screen orientation changes in Android.

Updated on: 09-May-2023

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements