10

When working with fragments, I have been using a class composed of static methods that define actions on fragments. For any given project, I might have a class called FragmentActions, which contains methods similar to the following:

public static void showDeviceFragment(FragmentManager man){
 String tag = AllDevicesFragment.getFragmentTag();
 AllDevicesFragment fragment = (AllDevicesFragment)man.findFragmentByTag(tag);
 if(fragment == null){
 fragment = new AllDevicesFragment();
 }
 FragmentTransaction t = man.beginTransaction();
 t.add(R.id.main_frame, fragment, tag);
 t.commit();
}

I'll usually have one method per application screen. I do something like this when I work with small local databases (usually SQLite) so I applied it to fragments, which seem to have a similar workflow; I'm not married to it though.

How have you organized your applications to interface with the Fragments API, and what (if any) design patterns do you think apply do this?

gnat
20.5k29 gold badges117 silver badges308 bronze badges
asked Dec 11, 2012 at 4:27
1
  • 1
    Why do you have one class responsible for showing all kind of fragment? Shouldn't it be a static method inside Fragment class inside? Commented Mar 3, 2014 at 2:15

1 Answer 1

3

The accepted pattern is to have a factory method inside your custom fragment class (typically called newInstance() but hey dealer's choice). So your fragment class should look something like this:

public class MyFragment extends Fragment
{
 public static MyFragment newInstance()
 {
 MyFragment newFragment = new MyFragment();
 // add any bundle arguments here if needed
 return newFragment;
 }
 // rest of fragment class...
}

Then, when you create a fragment and add it to the backstack, instead of saying:

MyFragment fragment = new MyFragment();

You can use the factory method instead of the 'new' keyword.

answered Apr 22, 2014 at 20:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.