Hadi Samadbin
Hadi Samadbin

Reputation: 237

Go back to a Fragment from an Activity onBackpress

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?

Upvotes: 1

Views: 1310

Answers (3)

Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27237

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)

Upvotes: 0

Sam
Sam

Reputation: 21

Check Google documentation for findFragmentByTag() here.

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

Upvotes: 2

T.S
T.S

Reputation: 951

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.

Upvotes: 0

Related Questions