First of all read the well written documentation, it answers to your doubts.
I would share my personal pattern to convert existing Activity
to Fragment
- Create your on abstract Fragment class from which derive all drawer fragments, this can help to group common attributes
- Use a method like
selectItem()
on docs, it helps to explicit do a call at first run (showing the "home" fragment) and then fromonItemClick
- move inflating XML layout from
Activity.onCreate()
code toFragment.onCreateView()
(iesetContentView
toinflater.inflate(R.layout.my_layout, container, false)
, in many cases you can copy all code fromonCreate()
toonCreateView
- move initialization code from
Activity.onCreate()
toFragment.onActivityCreated()
, this is very useful when both Activity (including fragment) and the direct Fragment exist, for example if your app exposes a "Share with" action you continue to have the Activity that inside the XML includes a<fragment/>
and the fragment can be created from the drawer, too - if you need to communicate from Activity to Fragment and viceversa I suggest to create an interface and store it inside the 'onAttach()' (see google example)
Action bar items must be hidden when drawer is open, again take a look at example used in doc, here is very useful the interface to communicate from activity to fragment, the main activity can tell if drawer is open and the fragment can call the interface
public interface FragmentActivityStatus { public boolean isDrawerOpen(); }
The activity
public class MainActivity extends Activity implements FragmentActivityStatus {
@Override
public boolean isDrawerOpen() {
return drawerLayout.isDrawerOpen(drawerList);
}
}
The fragment
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
fragmentActivityStatus = (FragmentActivityStatus)activity;
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
boolean isMenuVisible = !fragmentActivityStatus.isDrawerOpen();
menu.findItem(R.id.my_menu).setVisible(isMenuVisible);
super.onPrepareOptionsMenu(menu);
}
Not related to fragment, in your code you declare class names as string, consider to create a Class
array if you refactor packages the code continue to work, then you can call the Class.getName()
to obtain the string to pass to Fragment.instantiate()
final Class<?>[] fragments = {
FragmentOne.class,
FragmentTwo.class,
FragmentThree.class};
Then
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main, Fragment.instantiate(MainDraw.this,
fragments[pos].getName()));
tx.commit();