Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate fragments to different files in android studio?

I am trying to develop an android app in android studio and I keep writing more and more fragments in the mainActivity class. My question is how to separate these to another file? Probably I am doing it in a wrong way and if so could somebody show me how should I do it?

My code:

public class MainActivity extends ActionBarActivity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks {
.
.
.
public static class PlaceholderFragment1 extends Fragment {...}
public static class PlaceholderFragment2 extends Fragment {...}
public static class PlaceholderFragment3 extends Fragment {...}
}
like image 222
DalekSupreme Avatar asked Feb 10 '15 10:02

DalekSupreme


1 Answers

Since they are static inner classes, AndroidStudio can easily refactor these for you. Select PlaceholderFragment1 (just put the text cursor on it) and press F6 (or right click the fragment name->refactor->move) and select `Move inner class [fragment name] to upper level', change the name and package if you want and hit refactor.

Having a static inner class for a Fragment is fine (will work technically), but if you want to reuse the fragment in another activity, best to refactor it out. Also, most people like to keep classes as small as possible, and if the function of the fragment is logically separate from the activity there is little reason to keep it as an inner class.

like image 138
FunkTheMonk Avatar answered Nov 15 '22 16:11

FunkTheMonk