I'm new to using fragments in Android. I'm working on an app using a sliding panel layout and I just came up with an idea for changing my fragments. I decided to create the following method:
private void changeFrag(Object newFrag){
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_secondpane, (Fragment) newFrag).commit();
}
I'm calling the method in the following way:
changeFrag(new myFragment());
Could this cause problems for me in the long run? I was hoping that by writing it this way, I could avoid extra code and hopefully cut down on any extra processing power the device would need for something like this:
Fragment frag;
frag= new myFragment();
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_secondpane, (Fragment) frag).commit();
1 Answer 1
You could make it more dynamic. Because this method adds the Fragment only to the R.id.fragment_secondpane
layout. If this is all what you desire, it's ok. Otherwise add a parameter for the layout. This way you can use your method to add a Fragment to different layouts.
Because every type of Fragment like ListFragment, DialogFragment or even a SherlockFragment is using Fragment as super class, you can use Fragment
as the parameter type. There's no need to use Object
. Note that you should avoid to mix the Fragment types of different librarys.
With methods like this you can avoid extra code in this situation, replacing different Fragments of a specific layout.
The processing will be the same. The creation of the necessary objects have to be done. There will be no difference if this happens in e.g. onCreate or the method you wrote. The only thing you could avoid is to hold an extra reference of the FragmentManager.
To sum all up you would have something like this:
private void changeFrag(int layout, Fragment newFrag){
getSupportFragmentManager() // gets the FragmentManager of the Activity, no need to hold a reference
.beginTransaction()
.replace(layout, newFrag) // use the layout and the fragment, no need for a cast
.commit();
}
Note that this method will work and is straightforward. If you have an approach with adding some Fragments to the backstack and some not or using different kind of animations, your method will be more complex and lacks performance. That's why I would not use this in every situation.
-
\$\begingroup\$ Thank you very much for your input I appreciate everyone's help on this! \$\endgroup\$Chillie– Chillie2013年10月07日 13:53:35 +00:00Commented Oct 7, 2013 at 13:53
newFrag
asObject
, notFragment
? \$\endgroup\$frag
defined? Is itnewFrag
in the first block andfragment
in the second? If so, both blocks look identical save for putting the code into a method. \$\endgroup\$