Android: Go back to previous activity

2018-12-31 09:19发布

I want to do something simple on android app. How is it possible to go back to a previous activity.

What code do I need to go back to previous activity

23条回答
无色无味的生活
2楼-- · 2018-12-31 09:54

Just write on click finish(). It will take you to the previous Activity.

查看更多
与君花间醉酒
3楼-- · 2018-12-31 09:54

I suggest the NavUtils.navigateUpFromSameTask(), it's easy and very simple, you can learn it from the google developer.Wish I could help you!

查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 09:56

Try Activity#finish(). This is more or less what the back button does by default.

查看更多
牵手、夕阳
5楼-- · 2018-12-31 09:56

if you want to go to just want to go to previous activity use

finish();

OR

onBackPressed();

if you want to go to second activity or below that use following:

intent = new Intent(MyFourthActivity.this , MySecondActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Bundle is optional
Bundle bundle = new Bundle();
bundle.putString("MyValue1", val1);
intent.putExtras(bundle);
//end Bundle
startActivity(intent);
查看更多
泛滥B
6楼-- · 2018-12-31 09:58

Start the second activity using intent (either use startActivity or startActivityForResult according to your requirements). Now when user press back button, the current activity on top will be closed and the previous will be shown.

Now Lets say you have two activities, one for selecting some settings for the user, like language, country etc, and after selecting it, the user clicks on Next button to go to the login form (for example) . Now if the login is unsuccessful, then the user will be on the login activity, what if login is successful ?

If login is successful, then you have to start another activity. It means a third activity will be started, and still there are two activities running. In this case, it will be good to use startActivityForResult. When login is successful, send OK data back to first activity and close login activity. Now when the data is received, then start the third activity and close the first activity by using finish.

查看更多
人间绝色
7楼-- · 2018-12-31 10:02

If you have setup correctly the AndroidManifest.xml file with activity parent, you can use :

NavUtils.navigateUpFromSameTask(this);

Where this is your child activity.

查看更多
登录 后发表回答