problem in activity finish() and on pressing back button in android

安稳与你 提交于 2019-12-06 13:29:19

问题


I am very confused in using finish() for activity and using back button of keypad.I have created many activities so on moving from one activity to another I finish the last activity. And also I have used back button in my activity so I can go back (from where I came) by pressing back button but problem arises when I use keypad's back button I go to any other activity .I want it should work as my activity's back button.

And I think this can be done by using onKeyListener and chekcing keypad's back buttons and there I start activity same as my activity's back button. I want to know is it right to do this way or there is a way better than this?

Please Help


回答1:


There is a better way:

You should not call finish() when going from one activity to another. If the memory is needed, the OS will clear it for you, and when you press back it will work as needed. Just make sure your lifecycle functions are correct (you clean up big chunks of memory hogging stuff when you loose focus etc), and you'll be a much happier coder .




回答2:


You can override the activity's onBackPressed method to override the default behavior (which is to call finish() for your activity).

You should question your overall design when you are doing this on a routine basis, however. Please review the documentation on Tasks and Back Stack for other methods of controlling the user experience that work better with Android's activity lifecycle.




回答3:


Try not to use finish(), iF YOU WANT TO FREE MEMORY THEN DON'T WORRY ABOUT THAT os WILL DO THAT IN CASE MEMORY IS NEEDED AND BACK BUTTON WILL WORK TO.

I hope you know the life cycle of activity. Whenever you press the back button the other activity stops




回答4:


If you want to call finish() and also want your device back button work as activity back button then override the onBackPressed() method.

Suppose you are in Activity 2 and and want to back in Activity 1 which is your first actvity then inside Activity2.java write below code ....

public void onBackPressed()
    {
        Intent setIntent = new Intent(this,Activity1.class);
        startActivity(setIntent); 
        return;
    } 


来源:https://stackoverflow.com/questions/6353722/problem-in-activity-finish-and-on-pressing-back-button-in-android

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