Reputation: 398
I am new to android development.Recently i started developing apps using fragments.I did search some tutorials and tried working with fragments.In my app i am using a navigation drawer.Now suppose if user is on frag A and if the user again selects frag A the frag A is again created leaving the previous frag A in back stack.Now how should i construct my frag to make it very optimize.
Code which i have written
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();
}
I have made a master class which extends fragments and this master class is extended by other class.Now is my approach right???
Upvotes: 0
Views: 56
Reputation: 657
Your approach is right. I have implemented with same approach like this.
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();
}
}
Hope this will help you...
replace your "startFragment" method with "replaceFragment" and extend MasterFragment where you want
Upvotes: 1