I have a layout in xml.
In my activity, in the onCreate method i get a reference to the view i want to update periodically like this:
TextView myText = (TextView)findViewById(R.id.textview1);
Then, in a periodic method, i do this:
myText.setText(Float.toString(myData));
It works fine, until the screen rotates.
I read that when the screen rotates, the layout is recreated, and all the views on the layout are recreated, so the old references don’t work.
My code:
private TextView myText; //Its a class member
public void onCreate(Bundle savedInstanceState) {
//Other things
myText = (TextView)findViewById(R.id.textview1);
//Other things
}
//This is the periodic method, it occurs many times per second
public final void onSensorChanged(SensorEvent event) {
myText.setText(Float.toString(event.myData));
//This setText works fine until the screen rotation
}
How can i have a permanent reference to the view?
And how can i know when the screen has rotated?
Thanx
You might be thinking about things a little incorrectly if you want a permanent reference. The view is removed from memory when the phone is rotated (assuming you allow rotation.)
At the point of rotation you will need to get a pointer to the newly created object.
To detect orientation changes related to layout use onConfigurationChanged as shown in this post.
How to detect orientation change in layout in Android?