Android – Remove back button from action bar for a particular fragment

I have an app (Java) which loads a fragment (Fragment A). This fragment has a recyclerView which in turn loads a second fragment (Fragment B). I want Fragment B to have a back arrow that can return to Fragment A, but I don’t want the back arrow in Fragment A.

I added this code to the Main Activity:

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

But this causes the back arrow to appear in every fragment.

How can I have the back arrow appear only on second level fragments (like B)?

Answer

you can hide the button on the wanted fragment like this

@Override
public void onResume() {
    super.onResume();
    ((AppCompatActivity)getActivity()).getSupportActionBar(). setDisplayHomeAsUpEnabled(false);
}

@Override
public void onStop() {
    super.onStop();
    ((AppCompatActivity)getActivity()).getSupportActionBar(). setDisplayHomeAsUpEnabled(true);
}