1

I Tried the following code to move from a Fragment extends Fragment to an Activity extends activity.

 Intent mIntent = new Intent(getActivity(), UserProfile.class);
            Bundle bundle = new Bundle();
            bundle.putBoolean(Constant.isFromChatScreen, false);
            mIntent.putExtras(bundle);
            startActivity(mIntent);

In BaseActivity.java I have Fragment A, Fragment B, Fragment C..from Fragment A I moved to Userprofile.java now I want to move back to Fragment A onBackPressed How can I do that?

Hadi Samadbin
  • 237
  • 3
  • 17

3 Answers3

2

Check Google documentation for findFragmentByTag() here.

You can also use addToBackStack() while calling the fragment from FragmentTransaction

spmno
  • 805
  • 7
  • 13
Sam
  • 21
  • 4
0

Just use addToBackStack(null) before commit when you make fragment transactions and then when you press the back button you will get back to your fragment.

T.S
  • 911
  • 8
  • 24
  • He is starting a new Activity. You have to take in consideration how the lifecycle of the activity changes. – Murat Karagöz Dec 01 '16 at 13:56
  • You can see the comment of Hadi Samadbin with the link that says that my answer is correct. He is starting a new Activity and if he press the back button he will get to the last acitivity he was (which is the activity that include fragment A), and if he will addToBackStack the transitions, he will see fragment A because it was the last fragment he worked with before starting an intent to the new activity. – T.S Dec 01 '16 at 15:18
0

Old question, but anyone looking for an answer to this can just do this:

@Override
public void onBackPressed() {
  finish();
}

finish() "closes" the current Activity and takes you back to the Fragment (Actually, it takes you back to the Activity hosting the Fragment)

Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132