JavaSheriff
JavaSheriff

Reputation: 7677

Use single Fragment for multiple UI tasks?

I am using the Fragment master detail architecture
All Fragment Classes have the same logic
Is it possible to "detach" the Fragment from the layout and use just one Fragment class
So this code:

FragmentTransaction fragManager = getSupportFragmentManager().beginTransaction();

        if("001".equalsIgnoreCase(id)){
                    arguments.putString(Fragment001.ARG_ITEM_ID, id);
                    Fragment001 fragment = new Fragment001();
                    fragment.setArguments(arguments);                       fragManager.replace(R.id.item_detail_container, fragment);
        }
        else if("002".equalsIgnoreCase(id)){
                    arguments.putString(Fragment002.ARG_ITEM_ID, id);
                    Fragment002 fragment = new Fragment002();
                    fragment.setArguments(arguments);
                    fragManager.replace(R.id.item_detail_container, fragment);
        }

        fragManager.commit();

Will turn into Something like:

FragmentTransaction fragManager = getSupportFragmentManager().beginTransaction();               
                    GenericFragment fragment = new GenericFragment();                       
                    fragment.setUiId(id)
                    fragManager.replace(R.id.item_detail_container, fragment);
fragManager.commit();
  1. List item

Upvotes: 2

Views: 190

Answers (1)

Sam
Sam

Reputation: 546

yes its possible, you can check and select which layout to use in onCreateView...

public static final String ARG_ITEM_ID1 = "fragment001";

public static final String ARG_ITEM_ID2 = "fragment002";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
         Bundle savedInstanceState) {
     View rootView = null;
     String id = "fragment001";
     if(ARG_ITEM_ID1.equalsIgnoreCase(id)){

         rootView = inflater.inflate(R.layout.fragment_1_layout, container, false);
     }
     else {

        rootView = inflater.inflate(R.layout.fragment_2_layout, container, false);
     }
     return rootView;
}

Upvotes: 3

Related Questions