Set and display back arrow button in android

In android the back arrow button in the actionbar is one of the most useful the application . Using this icon user can direct from one activity to previously opened activity or is some cases if we want to give alert message while closing an activity.

You don’t want to use an ImageView or Button for displaying a back button. You just need to add the following code into your onCreate method of your activity.

getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Now you can give the functionality in your onOptionsItemSelected(MenuItem item) method like below

if (id == android.R.id.home) {
// your action on pressing back button

// here i am finishing activity

finish();
return true;
}

If you don’t have a menu in your activity use the below code

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == android.R.id.home) {
// your action on pressing back button

// here i am finishing activity

finish();
return true;
}

return super.onOptionsItemSelected(item);
}

Note: You need to have an xml file in your res/menu/ folder.

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *