Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android back button not working in fragment

I am new to android, I am called fragment_1 from my MianActivity then I am called fragment_2 from fragment_1. That is working fine. When I Press back button from fragment_2 it's not working (I want to go back to fragment_1)

   Fragment someFragment = new Fragment2();
   FragmentTransaction transaction = getFragmentManager().beginTransaction();
   transaction.replace(R.id.relative_layout_to_replace, someFragment );
   transaction.addToBackStack(null);
   transaction.commit();
like image 804
byteC0de Avatar asked Dec 10 '25 19:12

byteC0de


1 Answers

If you are using toolbar back buttons, then, make sure you have this code in your fragment:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //required for back button to work
    setHasOptionsMenu(true);
}

And also override this function:

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.i(TAG,"Back Button Pressed");
        switch (item.getItemId()) {
            case android.R.id.home:
                Log.i(TAG,"home on backpressed");
                getActivity().onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
like image 97
Reejesh PK Avatar answered Dec 13 '25 00:12

Reejesh PK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!