我已经在我的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(当前活动)正在工作的上下文?


当前回答

如果你在Cordova插件中调用共享意图,设置标志将不起作用。而是用这个——

cordova.getActivity().startActivity(Intent.createChooser(shareIntent, "title"));

其他回答

当startactivity不知道哪个是他的activity时,就会出现这个错误。所以你必须在startActivity()之前添加activity

你必须设置

context.startActivity(yourIntent);

给所有服用沙玛林的人。Android (MonoDroid)甚至当StartActivity从activity被调用时-这实际上是Xamarin bug与新的ART运行时,请参阅https://bugzilla.xamarin.com/show_bug.cgi?id=17630

我认为也许你在错误的地方实现OnClickListener -通常你应该在你的活动中实现OnItemClickListener,并将其设置在ListView上,否则你会遇到事件问题…

另外:如果你在listview中以片段的形式显示链接,不要这样创建它

adapter = new ListAdapter(getActivity().getApplicationContext(),mStrings);

而不是打电话

adapter = new ListAdapter(getActivity(),mStrings);

适配器在这两种情况下都工作得很好,但链接只在最后一种情况下工作。

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

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);