Android back button problem

谁说胖子不能爱 提交于 2019-12-06 16:15:25

问题


Say I have 3 Activities in my application: A, B and C. The flow though the application is: A -> B -> C.

Once at C, pressing the back button will take the user to B. If the user presses the back button another time they got to A, and finally if they press it one more time, they exit the application.

Objective: When the user presses the back button on C, they should go to A and not B, and if they press it another time, they exit the app.

Problem: When overriding the back button on Activity C to launch Activity A everything appears to be ok. However if the user presses the back button again, they return to Activity C. And so pressing the back button just switches between Activity A and Activity C.

I guess the Activity stack looks like:

  • Open app: A
  • Go to B: A, B
  • Go to C: A, B, C
  • Press back: A, B, C, A
  • Press back: A, B, C
  • Press back: A, B, C, A
  • Press back: A, B, C
  • Press back: A, B, C, A
  • Press back: A, B, C
  • Press back: A, B, C, A
  • ...etc

So it seems the mistake is to launch a new Activity when the back button on C is pressed? Anyway, I could do with advice on how to implement this behaviour.

Thanks, Jack


回答1:


You can add finish() in the onStop() method of activity B.

This way, when the activity B will no longer be visible, it will be destroyed and removed from the stack.

  • Open app: A
  • Go to B: A, B
  • Go to C: A, C
  • Press back: A
  • Press back: exiting



回答2:


When you go Activity B to Activity C first finish activity B then go activity C.

ex:-

finish();
Intent i2 = new Intent(Acttivity.B, Acttivity.C);
startActivity(i2);


来源:https://stackoverflow.com/questions/6609045/android-back-button-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!