I have two activities named Home and Cart. When I press a button in activity Home it goes to activity Cart.
For that I used the following Code
public void onClick(View v) {
开发者_如何学JAVAIntent intent = new Intent(this, Cart.class);
startActivity(intent);
}
In Cart activity when I press a button it comes to activity Home.
For That
public void onClick(View v) {
Intent intent = new Intent(this, Home.class);
startActivity(intent);
}
Activities are changing fine but the onCreate
method calls every time the activity starts.
Is that a fine life cycle of Activity or not? If not, how can I solve this?
How to solve what? That is the intended behavior of activities. Nevertheless, if you do not want that the methods in your onCreate method are called, you could use a flag like this:
public class YourActivity extends Activity {
private boolean firstStart = true;
public void OnCreate(...) {
if (firstStart) {
//do your stuff here
firstStart = false;
}
}
}
Consider using TabHost if you have two activities run simultaneously.
For solving your problem you have to understand the activity life cycle and which are the activity life cycle methods are called when switching from one activity to another activity.
No, I think that the cycle isn't correct in this case.
With this design, you may end up with a stack of activities which grows constantly, eg: Home -> Cart -> Home -> Cart -> Home -> Cart -> etc...
Pressing the Back button will then cycle back through each item in this stack.
I don't think that's what you want. If the user is at Home, then goes into the Cart, he's likely to press Back to go back to Home. Now the stack only contains Home, pressing Back again will exit, which sounds correct. And given the snippet that you show, I think that the exact same thing should happen when the use presses this button that you mention in Cart.
So, you need to call finish() in Cart, in order to go back to Home. You shouldn't rely on onSaveInstanceState() for restoring the contents of the cart. You could for example use an SQLite database for this.
onCreate() will be called whenever the Cart is launched, but it will only be called once in Home.
But the real thing is that you shouldn't even have that button to go back from the Cart to Home. This is maybe how one does things on iOS, but on Android, we have the Back button for this, users know it, use it, and there's no need for replicating this button on the screen.
精彩评论