问题
I've got an activity that shows some item from a list.
When swiping from right to left the same activity is started with the next product and when swiping from left to right I start the same activity with the previous product.
I get the product position from a global array using a member variable position
that I decrement when going to previous product and increment when going to next product, and that I pass as an extra in the intent.
The issue is that when pressing the back button, the position
value remains the same as that in the activity where I'm coming from. I understand that onResume is called instead of onCreate and that no extra is passed, but position
is not static and I expect it to keep its value in the activity instance. Why is this not the case?
Thanks
public class ProductHome extends Activity{
private int position;
private Product product;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_home);
position = getIntent().getIntExtra("Position", -1);
product = GlobalData.map_products.get(product_id);
// swipe detector
// left -> right: position++
// right -> left: position--
// then starts same activity again
gestureDetector = new GestureDetector(new SRPGestureDetector());
gestureListener = new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if (gestureDetector.onTouchEvent(event))
{
return true;
}
else{
return false;
}
}
};
RelativeLayout product_home = (RelativeLayout) findViewById(R.id.product_home);
product_home.setOnTouchListener(gestureListener);
}
}
回答1:
This has to do with the mode you launch your activity in. Most likely, there is only one instance of your activity.
You probably should not launch a new activity when slinging to the right, and probably not use the back button to go back to the previous product, but rather to the list where you probably com from
来源:https://stackoverflow.com/questions/7913093/issue-with-member-variable-of-an-activity-when-using-back-button