ojas
ojas

Reputation: 2210

Activity is not closed on clicking back button of Toolbar

Refer Below Image, enter image description here
I want to go back to the previous activity.
But on clicking the back button on toolbar,Nothing is happening.
I have used the following code to achieve that still no luck.

public boolean onOptionsItemSelected(MenuItem item){
       if(item.getItemId() == R.id.home)
       {
           finish();
       }
      return true;
    }

Upvotes: 6

Views: 5161

Answers (3)

Sinh Phan
Sinh Phan

Reputation: 1266

Add onBackPressed() method on your Activity. And super this. And when click back button call to this.onBackPressed(). Update code for this:

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

@Override
public void onBackPressed() {
    super.onBackPressed();
}

Upvotes: 0

QuinnChen
QuinnChen

Reputation: 730

In your OnCreate method

    toolbar.setTitle(R.string.title_activity_setting);
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

In your onOptionsItemSelected method

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

I will work.

Upvotes: 3

Tosin Onikute
Tosin Onikute

Reputation: 4002

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                //NavUtils.navigateUpFromSameTask(this);
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

Upvotes: 16

Related Questions