How to press back button in android programmatically?

余生长醉 提交于 2019-11-27 11:24:41

问题


In my app I have a logout functionality. If user clicks logout it goes to home screen. Now I am exiting my app by pressing back button. But what I want is I need to exit automatically(i.e Programmatically) as same like as back button functionality. I know by calling finish() will do the functionality. But the thing is it goes to the previous activity.


回答1:


onBackPressed() is supported since: API Level 5

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        onBackPressed();
    }
}

@Override
public void onBackPressed() {
    //this is only needed if you have specific things
    //that you want to do when the user presses the back button.
    /* your specific things...*/
    super.onBackPressed();   
}



回答2:


You don't need to override onBackPressed() - it's already defined as the action that your activity will do by default when the user pressed the back button. So just call onBackPressed() whenever you want to "programatically press" the back button.

That would only result to finish() being called, though ;)

I think you're confused with what the back button does. By default, it's just a call to finish(), so it just exits the current activity. If you have something behind that activity, that screen will show.

What you can do is when launching your activity from the Login, add a CLEAR_TOP flag so the login activity won't be there when you exit yours.




回答3:


Sometimes is useful to override method onBackPressed() because in case you work with fragments and you're changing between them if you push backbutton they return to the previous fragment.




回答4:


Call onBackPressed after overriding it in your activity.




回答5:


you can simply use onBackPressed();

or if you are using fragment you can use getActivity().onBackPressed()




回答6:


Simply add finish(); in your first class' (login activity) onPause(); method. that's all



来源:https://stackoverflow.com/questions/10718789/how-to-press-back-button-in-android-programmatically

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