我们如何在不重新创建的情况下完美地切换片段。我使用下面的代码来切换黑白两个片段。在第一个片段中,我通过在片段的 onViewCreated()中使用http请求实现了feed帖子。还有第二个片段以及其他一些选项,但是当我从第二个切换回第一个片段时。 httpRequest执行人员再次重复并重复
饲料。但是,当我从第一切换到第二个片段时,它没有发生。
我用
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());
}
}
答案 0 :(得分:0)
您可以将HTTP响应另存为成员变量,并且仅在onViewCreated中执行HTTP请求(如果该请求为null)
private String httpResponse;
public void onViewCreated (View view, Bundle savedInstanceState) {
if (httpResponse == null) {
// make HTTP request here
}
}