How to implement android Toolbar Back button

Zach picture Zach · May 19, 2016 · Viewed 37.8k times · Source

I am using a custom toolbar. I need to add back button to it. Now I am using this code to add the back button.

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        toolbar.setBackgroundColor(getResources().getColor(R.color.white));
        toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

This works fine. I can see the back button added. But consider the case where I am in Fragment1 which has no back button. Now I move to Fragment2 and I add in Back Button. From Fragment 2 I open Fragment 3 and I add the back button again.

Now when I press back button from fragment3 to go back to fragment2 i have to check the Fragment Stack to see whether the back button is required in fragment 2 or not.

Is there any other way to handle back button automatically as we push fragments to stack?

Answer

Masum picture Masum · May 19, 2016

Just add two new line of code. Something like this

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setBackgroundColor(getResources().getColor(R.color.white));
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));

setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        onBackPressed();
    }
});