Android: Remove a series of Activites on clicking back

大憨熊 提交于 2020-01-21 19:19:51

问题


Hello my application works like this now..

Main -> SEARCH -> ActivityA -> SEARCH -> ActivityB

And when I click back from ActivityB, I want to do the following

Main <- SEARCH <- ActivityB

i.e I want to skip activities ActivityA and SEARCH. I know I have to use the FLAG, but how?


回答1:


may be this be helpful Android: Clear the back stack




回答2:


You coud just do:

In SearchActivity

Intent i = new Intent(this, ActivityA.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(i);

In ActivityA

Intent i = new Intent(this, SearchActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(i);

which will take you back from B to Search and then to Main on two presses of the back button.

However

If you go from Main to Search to A to Search and then hit the back buttons, you would go from Search to Search to Main. (Two instances of search, probably not what you want)

It's better to set the flags in Activity A to be:

Intent i = new Intent(this, SearchActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);

This will stop the above behaviour and still give you what you want when you hit back from B




回答3:


I just had to override the back button in SEARCH activity like so

 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event)  {
     if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
         Log.d(TAG, "back pressed");
         Intent intent = new Intent(this, MainActivity.class);
         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         startActivity(intent);
     }
     return super.onKeyDown(keyCode, event);
 }


来源:https://stackoverflow.com/questions/5802089/android-remove-a-series-of-activites-on-clicking-back

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