我的应用仅在某些 Activity 中使用抽屉导航。我不想在每个 Activity 中重复代码,而是想修改它们扩展的基本 Activity ,以便抽屉导航代码仅位于一个位置。问题是onItemClick
方法将根据 Activity 而有所不同。例如,在 MainActivity
中按“Home”不应该做任何事情,因为我们已经在“家”了。按 ListActivity
中的“主页”应该带我去MainActivity
。
(请参阅我对我自己的问题 here 的回答以获取更多信息。当用户导航离开每个 Activity 时,我将完成每个 Activity ,并传递一个额外的内容以通知下一个 Activity 调用的 Activity 是什么。这这样做是为了避免当用户通过设备后退按钮返回时抽屉关闭的动画。这样,当他们返回时,抽屉完全关闭而没有动画,因为 Activity 已重新启动。)
我该怎么做才能向父类(super class)获取必要的信息?我需要每个子类将某种信息传递给父类(super class)。也许每个子类都可以传递一个 int 来向父类(super class)标识自己,而父类(super class)可以使用该 int 来确定在每种情况下要做什么?如果可能的话,我不确定如何做到这一点。
可能的父类(super class) BaseActivity
实现:
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
}
}
}
}
});
我怎样才能通过必要的int
从子类到父类(super class)?
BaseActivity
是抽象的:
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();
}
}
}
子类将只有这个实现:
public class MainActivity extends BaseActivity
{
//how to pass some parameter to BaseActivity from here?
@Override
protected Fragment createFragment()
{
return new MainFragment();
}
}
如果我不清楚,请告诉我。我很感激任何帮助。谢谢!
最佳答案
I would need each of the subclasses to pass some sort of information to the superclass to determine the implementation of onItemClick
您可以创建要在子类中使用的 protected 变量。
父类(super class)
中的示例:
protected boolean isLogin = false;
然后就可以在子类
的onItemClick
中设置isLogin
的值了。
更新
看来您需要知道什么类
通过使用实例
扩展了父类(super class)
。示例:
if(this instance of MainActivity.class)
关于java - 将信息从子类传递到父类(super class)以确定 NavigationDrawer onItemClick 的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26857285/