Search code examples
javaandroidif-statementandroid-intentback-button

How to start Intent when either actionbar or builtin back button is pressed


So I have an intent that I want to start when either of 2 back buttons is pressed. Either this back button "getSupportActionBar().setDisplayHomeAsUpEnabled(true);" or the one that's on all android phones that's built in to the device. I've searched around and could not find a solution.

Here's my code where you can see in the if statement I want the "if back button is pressed" code to be. I appreciate any input!

    CheckBox routeCheckBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_route_details);

    //back button for route details view
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //sets actionbar title
    routeName = getIntent().getExtras().getString("routeName");
    getSupportActionBar().setTitle(routeName);


    ///////checkbox///////
    routeCheckBox = (CheckBox) findViewById(R.id.routeCheckBox);

    routeCheckBox.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view)
        {
          if (routeCheckBox.isChecked())
          {
              Intent check = new     Intent(RouteDetails.this,MainActivity.class);
              check.putExtra("checkImageResource", R.drawable.checkmark);

  /////////////////// ////////////     
              if ( actionbar back button or the built in backbutton on all   android devices is pressed)
              {
                  startActivity(check);
              } 
     ////////////////////////////////
          }
        }
    });

New code Edit:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    // your code here
    routeCheckBox.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view)
        {
            if (routeCheckBox.isChecked())
            {
                Intent check = new Intent(RouteDetails.this,MainActivity.class);
                check.putExtra("checkImageResource", R.drawable.checkmark);
                startActivity(check);
            }
        }
    });
}

Solution

  • @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        // your code here
    }