Reputation: 1341
I have a main activity in which I have a drawer and selectItem procedure to process item selection of the drawer:
public void selectItem(drawerItems position) {
if (Utils.userId != 0) {
switch (position) {
case userSettings:
Fragment frag = new UserSettings();
Bundle args = new Bundle();
args.putSerializable("loginmode", Utils.LoginMode.lmRegistered);
frag.setArguments(args);
Utils.replaceFragment(frag);
break;
case option2:
Utils.replaceFragment(new fragmentX());
break;
case option3:
Utils.replaceFragment(new fragmentY());
break;
}
mCurrentSelectedPosition = position.ordinal();
if (mCurrentSelectedPosition > 0) {
mDrawerListView.setItemChecked(mCurrentSelectedPosition - 1, true);//user settings is not part of drawer view
mDrawerListView.setSelection(mCurrentSelectedPosition - 1);
} else mDrawerListView.clearChoices();
setTitle(mDrawerItemTitles[mCurrentSelectedPosition]);
} else {
Toast.makeText(this, getString(R.string.no_active_user), Toast.LENGTH_LONG).show();
mDrawerListView.clearChoices();
}
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) mDrawerLayout.closeDrawer(GravityCompat.START);
}
This is working great as long as I'm working with the drawer, the thing is, I switch fragments also from within a fragment so then I call Utils.replaceFragment(new fragmentX());
but I'm missing all the other "fun" of selecting an item (title, item focusing etc.).
I wanted to move the selectItem also to the Utils class but I don't have a reference to mDrawerItemTitles, mDrawerListView, mCurrentSelectedPosition etc. I can add them to the Utils class but I was wondering if there is a cleaner, nicer way to achieve what I want.
Another option was to make selectItem public and reach it from the hosted fragment but again, I was wondering if there is a nicer/cleaner way.
Upvotes: 0
Views: 74
Reputation: 2430
You could communicate your fragments and your main activity using a callback. Here you have a good explanation with examples.
http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
Upvotes: 1