1

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

Nichs
  • 123
  • 1
  • 15

3 Answers3

1

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;
    }
tyczj
  • 71,600
  • 54
  • 194
  • 296
1

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);
}
Lorenzo Camaione
  • 505
  • 3
  • 15
0

// 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

P Yellappa
  • 436
  • 5
  • 11