Android screen rotation not working as expected

247 views Asked by At

I've read some Android documents that when we rotate the screen, the contents of user input is destroyed because of recalling onCreate method. So we need save/restore codes for data loss when rotation. I just tried a simple app with only one EditText. After entering some texts in the EditText, nothing is cleared(destroyed) after screen rotation.

Is it right the EditText content is not cleared after screen rotation? Why do we need save/restore codes for screen rotation?

Before rotation

After rotation

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editTextTextPersonName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="76dp"
        android:layout_marginTop="56dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

After rotation, I thought the user text should be cleared. But the user input is NOT cleared.

2

There are 2 answers

0
Enowneb On

Since you have provided an unique ID to your EditText, Android will handle the orientation for you with your EditText value being preserved.

If you do not provide the ID to your EditText, then the EditText value will be cleared.

0
kapil tk On

In the case of TextView and EditText. Both have data in it. When the screen orientation changes the data in the EditText remains, but TextView data is cleared.

<TextView 
     ... 
     android:freezesText="true" />

From documentation on freezesText. This will helps to keep the data in TextView.

<EditText
     ...
     android:saveEnabled="false"/>

The above property helps to handle the behavior of EditText.