我是Android开发的新手。最近我开始使用片段开发应用程序。我确实搜索了一些教程并尝试使用片段。在我的应用程序中我使用的是导航抽屉。现在假设用户是在frag A上,如果是用户再次选择frag A再次创建frag A,将前一个frag A保留在后栈中。现在我应该如何构建我的frag以使其非常优化。
我写的代码
public class MasterFragment extends Fragment {
protected static Context context;
private FragmentTransaction fragmentTransaction;
private ProgressDialog progressDialog;
protected View view;
private AlertDialog.Builder builder;
protected File file;
String fileSeperator = "/";
private InputMethodManager inputMethodManager;
private static String boundary = "*****";
private static String lineEnd = "\r\n";
private static String twoHyphens = "--";
private File f;
private String response;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
context = getActivity();
}
protected void startFragment(Fragment fragment, String fragName, String backStackName, boolean value) {
fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
fragmentTransaction.replace(R.id.frag_container, fragment, fragName);
if (value) {
fragmentTransaction.addToBackStack(backStackName);
}
fragmentTransaction.commit();
}
我已经创建了一个扩展片段的大师类,这个大师类被其他类扩展。现在我的方法是对的吗?
答案 0 :(得分:1)
你的方法是对的。我用这样的方法实现了。
public void replaceFragment (Fragment fragment){
try {
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
FragmentManager manager =getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null){
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
希望这会对你有帮助......
替换你的" startFragment"方法用" replaceFragment" 并将MasterFragment扩展到您想要的位置