Back Button in ActionBar of App

Generally switching from one activity to another activity hamburger icon is replaced with back arrow. I want to control the functionality of that arrow. I have seen many contents here but most of them were related to hardware's back button. How can I control that?

I am trying the functionality in case of fragments. Also I have Navigation drawer attached with the hamburger icon.

I tried this-

if(id == android.R.id.home){
        getSupportFragmentManager().beginTransaction().replace(R.id.main_container, new AmbulanceMap()).commit();
        getSupportActionBar().setTitle("Book A Ride");
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    }

but doesnt work as I hoped.

I want my back button to change the fragmentto previous fragment.

Upvotes: 2

Views: 142

Answers (2)

Valentun
Valentun

Reputation: 1711

I had the same problem once. Just like you, things like checking if Android.R.id.home is clicked didn't work. But I solved it using that:

Set navigation listener to toolbar:

toolbar.setToolbarNavigationClickListener(v -> onBackPressed());

If it should be within fragment:

  1. Create an public method in activity.
  2. In fragment's onAttach (or later) cast getActivity() to your activity and call method you was defined previously.

Example:

// YourActivity
public void setHomeListener(OnLickListener listener){
    toolbar.setToolbarNavigationClickListener(listener);
}

//Fragment's onCreate
((YourActivity)getActivity()).setHomeListener(v -> onBackPressed());

//Fragment's onDestroy
 ((YourActivity)getActivity()).setHomeListener(null);

And, of course, set home us up enabled to show back arrow.

EDIT

if you don't use labmdas u should use:

(YourActivity)getActivity()).setHomeListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        YourFragment.this.onBackPressed();
    }
});

Upvotes: 1

hacksy
hacksy

Reputation: 840

The back button of the ActionBar is a menuItem so you need to override onOptionsItemSelected like this:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case android.R.id.home:
            //Your back button logic here
            break;
    }
    return true;
}

Also don´t forget to add getSupportActionBar().setDisplayHomeAsUpEnabled(true); after setting the Toolbar

Upvotes: 0

Related Questions