我正在开发我的第一个 Android 应用程序,但有一个无法解决的问题。我检查了堆栈溢出,但找不到解决方案。
我有一个菜单,当选择菜单项时显示 4 个不同的 Activity 。 我还有一个管理菜单的类:
public class TabMenuManager {
final Context context;
public TabMenuManager(Context context) {
this.context = context;
}
public boolean handleTabMenuAction(int item) {
Log.d("Toolstrea", "TAB MENU HANDLED: " + item);
switch (item) {
case R.id.action_home:
handleHomeAction();
return true;
case R.id.action_reorder:
handleReOrderAction();
return true;
//.....
}
private void handleReOrderAction() {
if (this.context.getApplicationContext() instanceof ReOrderActivity) {
Log.d("Toolstream", "REORDER CLASSES THE SAME");
Intent reOrderIntent = new Intent(this.context, ReOrderActivity.class);
reOrderIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.context.startActivity(reOrderIntent);
}
else
Log.d("Toolstream", "REORDER CLASSES NOT THE SAME");
}
private void handleHomeAction() {
// Simmilar as one above
}
}
在所有 Activity 中,我都会显示我刚刚调用的菜单:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
TabMenuManager tmm = new TabMenuManager(getApplicationContext());
boolean success = tmm.handleTabMenuAction(item.getItemId());
if (!success) {
return super.onOptionsItemSelected(item);
}
return success;
}
这个类只是简单的显示 Activity ,但我想确保它不会呈现与当前 Activity 相同的 Activity 。 在这个例子中我使用:
this.context.getApplicationContext() instance of ReOrderActivity
但我也尝试过
this.context.getClass() == HomeActivity.class
它总是记录 Activity 不同。 它导致的问题是,如果我在 HomeActivity 中,我可以在菜单中按 Home,并且 HomeActivity 的另一个实例将添加到堆栈中,依此类推。
如何确保我只呈现该 Activity 的一个实例? 有更好的方法吗?
非常感谢。
最佳答案
在您的代码中,ReOrderActivity 的 this.context.getApplicationContext() 实例
永远不可能为 true。您应该将其更改为:ReOrderActivity 的 this.context 实例
您还需要更改在 onOptionsItemSelected 中创建 TabMenuManager 的方式。将其更改为: TabMenuManager tmm = new TabMenuManager(this);
关于java - 如何检查上下文当前正在运行的 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22357642/