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

12
  • actionbar.setHomeButtonEnabled, though you should be using the toolbar instead of the old actionbar
    – tyczj
    May 17, 2016 at 19:13
  • I'm getting an error in the code. It's written in red text. I think your code is wrong and I maybe wrong about that but do you have a different solution to this? Thanks in advance! May 17, 2016 at 19:15
  • oops sorry its setDisplayHomeAsUpEnabled
    – tyczj
    May 17, 2016 at 19:17
  • It's showing an error and suggested to rename the reference. May 17, 2016 at 19:21
  • well you reference is actionBar hopefully you didnt just copy and past exactly what I wrote
    – tyczj
    May 17, 2016 at 19:24

3 Answers 3

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;
    }
1
  • Thank you very much for your answer. It worked perfectly. May 19, 2016 at 7:56
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);
}
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.