Reputation: 35
I want to display a back button in the left corner of the action bar and I do not completely know where to make the change in the activity.java to make it visible and functional.
@Override
protected void onCreate(Bundle savedInstancesState){
super.onCreate(savedInstancesState);
setContentView(R.layout.activity_news);
ActionBar actionBar = getSupportActionBar();
actionBar.setIcon(R.mipmap.ic_launcher);
This is what I want to display. View Image
Upvotes: 1
Views: 136
Reputation: 525
Showing it is as simple as putting this under your onCreate method in your Activity:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Then to control that input put this in your Activity:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
//or do what you want
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
Upvotes: 1
Reputation: 436
// activity
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// fragments
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
It may helps some one
Upvotes: 0
Reputation: 73741
you have to enable it by doing
actionBar.setDisplayHomeAsUpEnabled(true);
then if you want it to do something you need to look for the click in the onOptionsItemSelected
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
//do something here
break;
default:
break;
}
Upvotes: 1