How to close activity and go back to previous activity in android

后端 未结 18 1857
孤独总比滥情好
孤独总比滥情好 2020-12-07 08:19

I have a main activity, that when I click on a button, starts a new activity, i used the following code to do so:

Intent intent = new Intent(this, SettingsAc         


        
18条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 08:45

    You can go back to the previous activity by just calling finish() in the activity you are on. Note any code after the finish() call will be run - you can just do a return after calling finish() to fix this.

    If you want to return results to activity one then when starting activity two you need:

    startActivityForResults(myIntent, MY_REQUEST_CODE);
    

    Inside your called activity you can then get the Intent from the onCreate() parameter or used

    getIntent();
    

    To set return a result to activity one then in activity two do

    setResult(Activity.RESULT_OK, MyIntentToReturn);
    

    If you have no intent to return then just say

    setResult(Activity.RESULT_OK);
    

    If the the activity has bad results you can use Activity.RESULT_CANCELED (this is used by default). Then in activity one you do

    onActivityResult(int requestCode, int resultCode, Intent data) {
        // Handle the logic for the requestCode, resultCode and data returned...
    }
    

    To finish activity two use the same methods with finish() as described above with your results already set.

提交回复
热议问题