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 10:12
@Override
public void onBackPressed() {
    super.onBackPressed();
}

and if you want on button click go back then simply put

bbsubmit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        onBackPressed();
    }
});
查看更多
长期被迫恋爱
3楼-- · 2018-12-31 10:12

All new activities/intents by default have back/previous behavior, unless you have coded a finish() on the calling activity.

查看更多
春风洒进眼中
4楼-- · 2018-12-31 10:13

From your FirstActivity call the SecondActivity using startActivityForResult() method

For example:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

In your SecondActivity set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.

For example: In secondActivity if you want to send back data:

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

If you don't want to return data:

Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();

Now in your FirstActivity class write following code for the onActivityResult() method.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}//onActivityResult
查看更多
无与为乐者.
5楼-- · 2018-12-31 10:15

Just this

super.onBackPressed();
查看更多
荒废的爱情
6楼-- · 2018-12-31 10:16

You can explicitly call onBackPressed is the easiest way
Refer Go back to previous activity for details

查看更多
不流泪的眼
7楼-- · 2018-12-31 10:17

Add this in your onCLick() method, it will go back to your previous activity

finish();

or You can use this. It worked perfectly for me

 @Override
  public boolean onOptionsItemSelected(MenuItem item) {
  int id = item.getItemId();

      if ( id == android.R.id.home ) {
         finish();
         return true;
       }

  return super.onOptionsItemSelected(item);
  }
查看更多
登录 后发表回答