我已经在我的Android应用程序中实现了一个ListView。我使用ArrayAdapter类的自定义子类绑定到这个ListView。在重写的ArrayAdapter.getView(…)方法中,我分配了一个OnClickListener。在OnClickListener的onClick方法中,我想启动一个新活动。我得到了一个异常:

Calling startActivity() from outside of an Activity  context requires the  
FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

我怎样才能得到ListView(当前活动)正在工作的上下文?


当前回答

你可以用addFlags而不是setFlags来实现

myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

根据文档,它做到了:

添加额外的标志到意图(或与现有的标志值)。


EDIT

当你使用可能改变历史堆栈的标志时要小心,Alex Volovoy的回答说:

...避免设置标志,因为它会干扰正常的事件和历史堆栈流。

其他回答

芬兰湾的科特林版本

val intent = Intent(Intent.ACTION_EDIT, ContactsContract.Profile.CONTENT_URI)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
this.startActivity(intent)

如果你因为使用创建选择器而出错,如下所示:

Intent sharingIntent = new Intent(Intent.ACTION_VIEW);
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sharingIntent.setData(Uri.parse("http://google.com"));
startActivity(Intent.createChooser(sharingIntent, "Open With"));

设置标志以创建选择器,如下所示:

Intent sharingIntent = new Intent(Intent.ACTION_VIEW);
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sharingIntent.setData(Uri.parse("http://google.com"));

Intent chooserIntent = Intent.createChooser(sharingIntent, "Open With");
chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(chooserIntent);

要么

通过适配器中的构造函数缓存Context对象,或者 把它从你的视图中取出来。

或者作为最后的手段,

添加FLAG_ACTIVITY_NEW_TASK标志到你的意图:

_

myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

编辑-我将避免设置标志,因为它将干扰正常的事件和历史堆栈流。

在我看来,最好在Activity.class的代码中使用startActivity()方法。如果您在适配器或其他类中使用它,则会导致该结果。

我也有同样的问题。检查您传递的所有上下文。对于“链接”,它需要活动上下文而不是应用程序上下文。

以下是你应该检查的地方:

1)。如果你使用了LayoutInflater,那么检查你传递了什么上下文。

2)。如果您正在使用任何适配器,请检查您传递的上下文。