My app uses a Navigation Drawer on only some activities. Instead of duplicating the code in each activity, I want to modify the base activity they extend so the navigation drawer code is only in one place. The problem is that the onItemClick
method will vary depending on the activity. For instance, pressing "Home" in MainActivity
should do nothing, since we're already at "Home." Pressing "Home" in ListActivity
should take me to MainActivity
.
(Please see my answer to my own question here for a little more information. I am finishing each activity when the user navigates away from it, and passing an extra to inform the next activity what the calling activity was. This was done to avoid the animation of the drawer closing when the user returns via the device back button. This way, when they return, the drawer is fully closed without animation because the activity has been restarted.)
What can I do to get the necessary information to the superclass? I would need each of the subclasses to pass some sort of information to the superclass. Maybe each subclass could pass an int which identifies itself to the superclass, and the superclass can use that int to determine what to do in each case? I'm not sure how to do that, if it is possible.
Possible superclass BaseActivity
implementation:
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView parent, View view, int position, long id)
{
//passedParameter is an int that the subclass passes to the superclass to identify itself
switch(int passedParameter)
{
//int passed from subclass identifies it as MainActivity
case MAIN_ACTIVITY:
{
switch(position)
{
//HOME
case 0:
//do nothing since we're already at MainActivity/home
//LIST
case 1:
//go to ListActivity
}
}
//int passed from subclass identifies it as ListActivity
case LIST_ACTIVITY:
{
switch(position)
{
//HOME
case 0:
//go to MainActivity
//LIST
case 1:
//do nothing since we're already at ListActivity
}
}
}
}
});
How could I pass the necessary int
from the subclass to the superclass?
BaseActivity
is abstract:
public abstract class BaseActivity extends FragmentActivity
{
protected abstract Fragment createFragment();
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
//navigation drawer code shown above, plus more
if (fragment == null)
{
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
And the subclass will have only this implementation:
public class MainActivity extends BaseActivity
{
//how to pass some parameter to BaseActivity from here?
@Override
protected Fragment createFragment()
{
return new MainFragment();
}
}
Please let me know if I am unclear. I appreciate any help. Thanks!