Reputation: 1362
How do you add a button to the default action bar in Android? I can get the bar with ActionBar a = getSupportActionBar(); however, I don't see how to add a left button (like a home button but do not want it to act as a home button).
Upvotes: 1
Views: 65
Reputation: 83
In onCreate use:
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
and Override with:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
Upvotes: 1
Reputation: 622
The other answer is correct on how to implement this, you can accomplish it that way. But without looking at your profile I'm going to guess you're coming from an iOS background because this is the iOS paradigm. You should take the time to learn Android paradigms if you're developing Android apps, otherwise you will confuse your users by presenting them a UI that breaks conventions they have become accustomed to. You can see more about these conventions on Android's documentation, i.e. https://developer.android.com/guide/topics/ui/look-and-feel
Upvotes: 1
Reputation: 3284
to add home button to your ActionBar just write this line
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and to handle click listener you can override onOptionsItemSelected()
like this
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//Do Something Here . . .
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Upvotes: 1