vanculix vanculix - 2 months ago 10
Android Question

Android Move to previous fragment without reload

I have a

HomeFragment
and
LoginFragment
in the same
Activity
. At first it shows the
HomeFragment
and then go to
LoginFragment
. But when I back to
HomeFragment
it reloads the
HomeFragment
.

How to make the
HomeFragment
not reload when I press back from
LoginFragment
.

Thanks in advance. Here is my code :

MainActivity.java

private void setEvent() {
img_action_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
closeKeyboard(getApplication(), img_action_back.getWindowToken());
onBackPressed();
}
});
}

@Override
public void onBackPressed() {
if (fragment instanceof LoginFragment)
{
LoginFragment loginFragment = (LoginFragment)fragment;
if(loginFragment.fromDrawer)
Navigator.showHomeFragment(mContext);
else
finish();
}
}
}


Navigator.java

public static void showHomeFragment(Context context) {
final FragmentTransaction transaction =
getFragmentManager(context).beginTransaction();
transaction.replace(CONTAINER_ID, new HomeFragment());
transaction.commit();
}

public static void showLoginFragment(Context context,Boolean fromDrawer,String infoRegister) {
final FragmentTransaction transaction =
getFragmentManager(context).beginTransaction();
transaction.replace(CONTAINER_ID,
LoginFragment.newInstance(fromDrawer,infoRegister),"login");
transaction.commit();
}

Answer

Your issue is that you're recreating a new HomeFragment instance when you press back. You should instead pop the FragmentManager backstack.

 @Override
 public void onBackPressed() {
     if (fragment instanceof LoginFragment) {
        LoginFragment loginFragment = (LoginFragment)fragment;
        if(loginFragment.fromDrawer) {
            getFragmentManager(mContext).popBackStack();
        } else {
            finish();
        }
    }
}

You also need to make sure you add the LoginFragment to the backstack.

public static void showLoginFragment(Context context,Boolean fromDrawer,String infoRegister)
{
   final FragmentTransaction transaction =
   getFragmentManager(context).beginTransaction();
   transaction.replace(CONTAINER_ID,
   LoginFragment.newInstance(fromDrawer,infoRegister),"login");
   transaction.addToBackStack(null);
   transaction.commit();
}
Comments