2

I created back arrow button via code:

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        View rootView = inflater.inflate(R.layout.w_output_power, container, false);

        calculatePower(rootView);

        return rootView;
    }

And I cannot implement functionality to go back to previous fragment when back arrow is pressed. I've seen that it should be done with method handleOnBackPressed() but I am not sure how exactly. Thanks for help in advance.

Antonio
  • 240
  • 3
  • 15

2 Answers2

0

There are two things that you need to ensure.

  1. Your fragments should be properly added to backstack, so that when you pop them while back pressing, it would show the previous fragment in the backstack Refer: Android Fragment handle back button press

  2. You need to call Activity's onBackPressed where you need to check if the fragment is the correct instance that you want to pop Refer: https://stackoverflow.com/a/46425415/980898

Madhan
  • 361
  • 4
  • 17
0

In yours Activity that holds this fragment u can write this

  @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
i30mb1
  • 3,894
  • 3
  • 18
  • 34