I realized that all standard views with an identifier should automatically save their state, and, trying this with an example, I found it rather confusing.
I had only 1 activity and the main layout, as indicated below.
When I change the text of a TextView by clicking on a button and then rotating the screen, the TextView really saves its state, but after rotating it again, it resets to the default state.
The same thing happens if I edit it during the landscape and rotate it: after the first rotation it saves its state, but after the other it rotates (unless I change the text again), it is reset to default.
I'm really confused. Can someone please explain this behavior to me. I could not find another question (or answer) that explains this particular behavior.
activity_main.xml:
<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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/activity_main_textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:maxLines="2" android:text="test" android:textSize="50sp" /> <EditText android:id="@+id/activity_main_editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:maxLength="30" android:maxLines="1" /> <Button android:id="@+id/activity_main_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:text="Set text" /> </RelativeLayout>
MainActivity.java:
package com.example.viewstatetest; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView textView; private EditText editText; private View button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.activity_main_textView); editText = (EditText) findViewById(R.id.activity_main_editText); button = findViewById(R.id.activity_main_button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView.setText(editText.getText()); } }); } }
source share