How can we perfectly switch fragments without recreating. Im using below code to switch b/w two fragments. In first fragment i have Implemented feed posts by using a http request in onViewCreated() of fragments.And i have a second fragment with some other options.But when i switch back to first fragment from second.. The httpRequest executives again and duplicates
Feed items.But when i switch to the second fragment from first its not happening. I use it like
FragmentUtils.changeFragment(fragHome,R.id.mobile_container, true,(AppCompatActivity)getActivity());
public static void changeFragment(Fragment frag,int v, boolean saveInBackstack,AppCompatActivity a) {
String backStateName = ((Object) frag).getClass().getName();
try {
FragmentManager manager = a.getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(backStateName) == null) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(v, frag, backStateName);
if (saveInBackstack) {
Log.d(TAG, "Change Fragment: addToBackTack " + backStateName);
transaction.addToBackStack(backStateName);
} else {
Log.d(TAG, "Change Fragment: NO addToBackTack");
}
transaction.commit();
} else {
// custom effect if fragment is already instanciated
}
} catch (IllegalStateException exception) {
Log.w(TAG, "Unable to commit fragment, could be activity as been killed in background. " + exception.toString());
}
}
You could save your HTTP response as a member variable and only perform your HTTP request in onViewCreated if that is null'
private String httpResponse;
public void onViewCreated (View view, Bundle savedInstanceState) {
if (httpResponse == null) {
// make HTTP request here
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.