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


当前回答

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

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

其他回答

面对同样的问题,然后实施

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

解决了这个问题。

可能还有另一个原因与列表视图适配器有关。 你可以看到这个博客,描述得很好。

CustomAdapter mAdapter = new CustomAdapter( getApplicationContext(), yourlist);

or

Context mContext = getAppliactionContext();
CustomAdapter mAdapter = new CustomAdapter( mContext, yourlist);

更改如下

CustomAdapter mAdapter = new CustomAdapter( this, yourlist);

我的情况有点不同,我正在使用Espresso测试我的应用程序,我必须从仪器环境中启动我的活动与ActivityTestRule(这不是一个来自活动)。

fun intent(context: Context) = 
    Intent(context, HomeActivity::class.java)
        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

我不得不改变标志,并添加一个或位(在Java中|)与意图。FLAG_ACTIVITY_NEW_TASK

结果是:

fun intent(context: Context) = 
    Intent(context, HomeActivity::class.java)
        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)

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

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

你必须设置

context.startActivity(yourIntent);