G K G K - 21 days ago 5
Android Question

how to override action bar back button in android?

here is my query
I want to customize the activity back button in action bar not in hard key back button?
I have override the onBackPressed() method it works with my emulator back button and not

with action bar back button.

I want it to happen with action bar? How can I do this?
Here is my code

@Override
public void onBackPressed()
{

Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return;
}


I have used this toast whether back pressed is working or not but the actual implementation changes like to move back to previous activity. but this is not working with the button present on Top of Action bar (Besides Title of the activity).

Please any one could specify me the problem.

Answer

I think you want to override the click operation of home button. You can override this functionality like this in your activity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show(); 
        break;
    }
    return true;
}