Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
like image 369
ojas Avatar asked Sep 16 '15 02:09

ojas


2 Answers

@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);
    }
like image 171
Tosin Onikute Avatar answered Oct 09 '22 23:10

Tosin Onikute


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.

like image 21
QuinnChen Avatar answered Oct 09 '22 23:10

QuinnChen