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();
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With