问题
This kind of questions appear periodically. Sorry if this has been covered before, but I'm a newbie and couldn't find the appropriate answer. It deals with the correct implementation of communication between classes and activities.
I made a gallery app. It has 3 main activities: the Main
one, to search for filenames using a pattern; a Thumb
one, that shows all the images that matched the pattern as thumbnails in a gridview, and a Photo
activity, that opens a full sized image when you click a thumb in Thumbs
. I pass to the Photo
activity via an Intent
the filenames (an array), and the position
(an int
) of the clicked thumb in the gridview.
This third Photo
activity has only one view on it: a TouchImageView
, that I adapted for previous/next switching and zooming according to where you shortclick on the image (left, right or middle). Moreover, I added a longclick listener to Photo
to show EXIF info.
The thing is working, but I am not happy with the implementation... Some things are not right.
One of the problems I am experiencing is that, if I click on the right of the image to see the next in the Photo
activity, it switches fine (position++
), but when rotating the device the original one at position
appears.
What is happening is that Photo
is destroyed when rotating the image, and for some reason it restarts again, without obeying super.onCreate(savedInstanceState)
, loading again the Extras (the position
only changed in Photo
, not on the parent activities).
I tried with startActivityForResult
instead of startActivity
, but failed...
Of course I can do something contrived to save the position
data, but there should be something "conceptual" that I am not understanding about how activities work, and I want to do this right.
Can someone please explain me what I am doing wrong, which is the best method to implement what I want, and why?
Thanks a lot!!!
回答1:
Try this code to store the values for the activity
Long value;
protected void onSaveInstanceState(Bundle onOrientChange) {
super.onSaveInstanceState(onOrientChange);
onOrientChange.putLong("myValue", value);
}
And restore the values in onCreate():
public void onCreate(Bundle onOrientChange) {
if (onOrientChange!= null){
value = onOrientChange.getLong("myValue");
}
}
Usually you restore your state in onCreate()
. It is possible to restore it in onRestoreInstanceState()
as well, but not very common. (onRestoreInstanceState()
is called after onStart()
, whereas onCreate()
is called before onStart()
.
Use the put methods to store values in onSaveInstanceState()
来源:https://stackoverflow.com/questions/13905641/passing-extras-and-screen-rotation