I was looking through an example in
I managed to incorporate that successfully in my app but I could not quite understand the onItemClick function.
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerLayout.closeDrawer(mDrawerList);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ftx = fragmentManager.beginTransaction();
if(position == 0) {
ftx.replace(R.id.main_content, new FragmentFirst());
} else if(position == 1) {
ftx.replace(R.id.main_content, new FragmentSecond());
}
ftx.commit();
}
From the raw code it'll create a new Fragment every time there is an item click in the drawer. I understand that if this was called the first time you'll need an instance of it. But wouldn't it make sense to save the fragment somewhere in the activity? Then switch to it upon item click?
Something like
Fragment fOne;
Fragment fTwo;
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerLayout.closeDrawer(mDrawerList);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ftx = fragmentManager.beginTransaction();
if(position == 0) {
if( fOne==null){
fOne = new FragmentFirst();
}
ftx.replace(R.id.main_content, fOne);
} else if(position == 1) {
if( fTwo==null){
fTwo = new FragmentSecond();
}
ftx.replace(R.id.main_content, fTwo);
}
ftx.commit();
}
0 comments:
Post a Comment