Action Bar's onClick listener for the Home button

How can I implement a custom onClickListener for the Home button of the Action Bar?

I already did a getSupportActionBar().setDisplayHomeAsUpEnabled(true); and now I want to redirect the user to a certain activity in case the Home button is clicked.

I tried with:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            item.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem item) {
                    Intent i = new Intent();
                    i.setClass(BestemmingActivity.this, StartActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                    return true;
                }
            });
        default:
            return super.onOptionsItemSelected(item);
        }
    }

but it never enters in the onMenuItemClick.

Basically, it's done just like in this link but still it doesn't enter in the listener.


Solution 1:

if anyone else need the solution

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

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

    return super.onOptionsItemSelected(item);
}

Solution 2:

I use the actionBarSherlock, after we set supportActionBar.setHomeButtonEnabled(true);
we can override the onMenuItemSelected method:

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {

    int itemId = item.getItemId();
    switch (itemId) {
    case android.R.id.home:
        toggle();

        // Toast.makeText(this, "home pressed", Toast.LENGTH_LONG).show();
        break;

    }

    return true;
}

I hope this work for you ~~~ good luck

Solution 3:

if we use the system given action bar following code works fine

getActionBar().setHomeButtonEnabled(true);

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {

    int itemId = item.getItemId();
    switch (itemId) {
    case android.R.id.home:
      //do your action here.
        break;

    }

    return true;
}