Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextView's text disappearing when device rotated

I am writing a phone dialer app for android. I created a layout for keypad, which contains a TextView and 10 buttons. Buttons are as keys for 10 digits(0 to 9) and TextView is for displaying the number according to keys pressed.

In my app, i am appending the text ("0" or "1", etc.) to the TextView for each button pressed. If i pressed the buttons 1, 2, 3 then the text on TextView is 123. The problem is, let's take the screen is in landscape mode and TextView contains 123, if i turn it, in portrait mode no text on TextView.

Please Help Me Regarding this.

like image 705
Yugandhar Babu Avatar asked Jan 16 '12 11:01

Yugandhar Babu


4 Answers

Please check on orientation change, on create method is called, which requires all the views to be created again, so you need to use one of the following methods:

  1. use onSavedInstance method and save the states of components/views to bundle.
  2. Just use following flag true in your manifest file in activity tag android:configChanges="keyboardHidden|orientation". like below:

    <activity android:name=".SampleActivity" android:label="@string/app_name"
        android:configChanges="keyboardHidden|orientation">
        ...
    </activity>
    
like image 137
jeet Avatar answered Oct 19 '22 17:10

jeet


The reason for this is due to Android basically destroying the activity and creating it again every time you rotate the device. This is mainly to allow for different layouts based on portrait/landscape mode.

The best way to handle this is to store whatever data you need to keep within the Activity Bundle, by responding to the onSavedInstance event (called just before Android destroys the activity), and then reapplying those in the standard onCreate event.

Although you can add "orientation" to the configChanges property, keep in mind that you're basically telling Android that you're going to be handling everything relating to orientation change yourself - including changing layout, etc.

like image 26
Digital_Utopia Avatar answered Oct 19 '22 17:10

Digital_Utopia


What @jeet recommended didn't work for me. I had to add "screenSize". This is the line you should add in your manifest.xml in the <activity> node of your activity:

android:configChanges="keyboardHidden|orientation|screenSize"

Thus, the complete node may look like this:

<activity
android:name=".YourActivity"
android:label="@string/app_name"
android:configChanges="keyboardHidden|orientation|screenSize"
android:theme="@style/AppTheme.NoActionBar">
like image 16
user160446 Avatar answered Oct 19 '22 17:10

user160446


To preserve a TextView's text, you can simply set the TextView's freezesText property to true. As in:

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

This is the accepted answer here: Restoring state of TextView after screen rotation?

like image 2
Sam Avatar answered Oct 19 '22 18:10

Sam