Alex F
Alex F

Reputation: 43311

TextView contents is lost after changing screen orientation

Observing my application behavior in Android emulator, I see that EditText contents is preserved after changing screen orientation (Ctrl+F11). But TextView contents is reset to its initial value and doesn't keep latest information set by the program. Is this behavior by definition? What can I do to keep this contents?

Upvotes: 10

Views: 5894

Answers (3)

Durairaj Packirisamy
Durairaj Packirisamy

Reputation: 4725

Use this property in your TextView android:freezesText="true".

Upvotes: 12

Andy
Andy

Reputation: 10830

When orientation changes happen, Android reload the Activity hence destroying most information like TextView changes. You will need to override onSaveInstanceState(), which will run before the screen orientation change happens. Then you will have access to it in your Bundle that is passed into onCreate. You should also reference this to understand the Activity Life cycle.

Upvotes: 3

biddulph.r
biddulph.r

Reputation: 5266

You can use the savedInstanceBundle to keep hold of the data by overriding two methods inside your activity, similar to below:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  // Save state to the savedInstanceState
  savedInstanceState.putString("MyString", textview.getText());

}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  // Restore state from savedInstanceState
  String myString = savedInstanceState.getString("MyString");
  textview.setText(myString);
}

Add your items to the Bundle in onSaveInstanceState, and read them back in during onRestoreInstanceState. This works in a similar way to passing values through intents when creating activities.

Upvotes: 13

Related Questions