Search code examples
androidandroid-intentandroid-activityfragment

Get back to a fragment from an Activity


I have three fragment in an Activity C. they are behaving as tabs. I have to go from a fragment to a new Activity X. Now i want to come back to fragment from Activity X.

I have override onBackPressed but don't know how to go back to fragment/not fragmentActivity from an Activity.

if i want to go back to an Activity to another activity i override on back pressed and using intent call that actvity..

i want to do some thing like this .. this code is for coming back to previous activity

@Override
public void onBackPressed()
{

    Intent intent = new Intent(CurrentActivity.this,ActivityYouLikeToGo.class);

    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

    startActivity(intent);
}

thanks in Advance..


Solution

  • You can add a TAG (A string name for the fragment basically) and then load the fragment using findFragmentByTag().

    Google documentation for findFragmentByTag() is here.

    Or you can also addToBackStack() while calling the fragment from FragmentTransaction, doc link here. from google docs:

    "By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button."