Android: Go back to previous activity

前端 未结 23 1577
抹茶落季
抹茶落季 2020-11-22 06:52

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条回答
  • 2020-11-22 07:32

    You can try this:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
  • 2020-11-22 07:32

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

    0 讨论(0)
  • 2020-11-22 07:33
    @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();
        }
    });
    
    0 讨论(0)
  • 2020-11-22 07:36

    Just try this in, first activity

    Intent mainIntent = new Intent(Activity1.this, Activity2.class);
    this.startActivity(mainIntent);
    

    In your second activity

    @Override
    public void onBackPressed() {
        this.finish();
    }
    
    0 讨论(0)
  • 2020-11-22 07:37

    There are few cases to go back to your previous activity:

    Case 1: if you want take result back to your previous activity then ActivityA.java

     Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
                   startActivityForResult(intent,2);
    

    FBHelperActivity.java

     Intent returnIntent = new Intent();
     setResult(RESULT_OK, returnIntent);
     finish();
    

    Case 2: ActivityA --> FBHelperActivity---->ActivityA

    ActivityA.java

     Intent intent = new Intent(ActivityA.this, FBHelperActivity.class);
                   startActivity(intent);
    

    FBHelperActivity.java

    after getting of result call finish();
     By this way your second activity will finish and because 
     you did not call finish() in your first activity then
     automatic first activity is in back ground, will visible.
    
    0 讨论(0)
  • 2020-11-22 07:38
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
          int id = item.getItemId();
    
          if ( id == android.R.id.home ) {
              finish();
              return true;
          }
    
          return super.onOptionsItemSelected(item);
     }
    

    Try this it works both on toolbar back button as hardware back button.

    0 讨论(0)
提交回复
热议问题