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


当前回答

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

其他回答

Intent i= new Intent(context, NextActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

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

如果使用数据绑定,只需获取上下文

binding.root.context

这解决了我的问题。

在你的Activity中(你调用适配器的地方),只需用YourActivity.this改变getActivityContext()。 这里有一个例子:

yourAdapter = new YourAdapter(yourList, YourActivity.this); // Here YourActivity.this is the Context instead of getActivityContext()
recyclerView.setAdapter(yourAdapter);

使用这段代码。对我来说没问题。分享活动之外的东西:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");

// Append Text
String Text = "Your Text Here"

intent.putExtra(Intent.EXTRA_TEXT, Text);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Intent shareIntent = Intent.createChooser(intent,"Share . . . ");
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
G.context.getApplicationContext().startActivity(shareIntent);