我已经在我的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所提到的,应该避免设置标志,因为它会干扰事件和历史堆栈的正常流程。

其他回答

在Android 28(Android P)启动活动

if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
        && (targetSdkVersion < Build.VERSION_CODES.N
                || targetSdkVersion >= Build.VERSION_CODES.P)
        && (options == null
                || ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) {
    throw new AndroidRuntimeException(
            "Calling startActivity() from outside of an Activity "
                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
                    + " Is this really what you want?");
}

所以最好的方法是添加FLAG_ACTIVITY_NEW_TASK

Intent intent = new Intent(context, XXXActivity.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);

我的情况有点不同,我正在使用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)

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

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

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

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

从视图的Activity上下文外部调用startActivity()

val context = activity.applicationContext
openBrowser(context, MenuUrl.TERM_CONDITION)

Do

   1. val context = binding.root.context // If you are using view binding
   2. val context = yourView.context // If you are not use view binding
    openBrowser(context, MenuUrl.TERM_CONDITION)

谢谢你!

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

or

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

更改如下

CustomAdapter mAdapter = new CustomAdapter( this, yourlist);