I experience some weird behaviour in an android app I am developing:
I have a class HintsMenu (snippet):
public class HintsMenu extends Fragment implements AbsListView.OnItemClickListener {
...
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static HintsMenu newInstance() {
System.out.println("HintsMenu.newInstance()");
HintsMenu fragment = new HintsMenu();
Bundle args=new Bundle();
args.putString(ARG_TITLE,"Hints");
fragment.setArguments(args);
return fragment;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public HintsMenu() {
System.out.println("Hintsmenu constructor");
}
This Fragment is dynamically used in an activity:
public class MainActivity extends ActionBarActivity implements MainMenu.NavigationDrawerCallbacks {
....
@Override
public void onNavigationDrawerItemSelected(MenuEntry item) {
// update the main content by replacing fragments
if (item.hasActivity()){
...
} else if (item.hasFragment()){
try {
FragmentManager fragmentManager = getSupportFragmentManager();
Class<? extends Fragment> cl=item.getFragmentClass();
System.out.println("Calling " + cl.getSimpleName() + ".newInstance()...");
Fragment newFragment=cl.newInstance();
fragmentManager.beginTransaction().replace(R.id.container, newFragment).commit();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
The idea is, that item.activityClass (code not shown) is set by the expression
item.fragmentClass=HintsMenu.class;
at another position in the code, and item.getFragmentClass() returns this value inside onNavigationDrawerItemSelected(). In "onNavigationDrawerItemSelected", a new HintsMenu is created using the cl.newInstance() call. However, HintsMenu's newInstance method is NOT called, but the empty Constructor is.
So insted of the expected output
Calling HintsMenu.newInstance()...
HintsMenu.newInstance()
Hintsmenu constructor
I only get
Calling HintsMenu.newInstance()...
Hintsmenu constructor
If i do
HintsMenu.newInstance()
I get the expected output. Can anyone tell me, what I am doing wrong?