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


当前回答

来自Xamarin的人。form或Xamarin。安卓,在你的Xamarin里。Android项目,使用:

Xamarin.Essentials.Platform.CurrentActivity.StartActivity(intent);

注意,这可能需要Xamarin。Essentials v1.5或以上版本

正如@Alex Volovoy所提到的,应该避免设置标志,因为它会干扰事件和历史堆栈的正常流程。

其他回答

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

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

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

芬兰湾的科特林版本

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

而不是使用(getApplicationContext)使用YourActivity.this

看,如果你在某个方法的监听器中创建一个意图

override onClick (View v).

然后通过这个视图调用context:

v.getContext ()

甚至不需要SetFlags…