从 Activity 上下文外部调用 startActivity() [英] Calling startActivity() from outside of an Activity context
问题描述
我在我的 Android 应用程序中实现了一个 ListView
.我使用 ArrayAdapter
类的自定义子类绑定到这个 ListView
.在重写的 ArrayAdapter.getView(...)
方法中,我分配了一个 OnClickListener
.在 OnClickListener
的 onClick
方法中,我想启动一个新活动.我得到了例外:
I have implemented a ListView
in my Android application. I bind to this ListView
using a custom subclass of the ArrayAdapter
class. Inside the overridden ArrayAdapter.getView(...)
method, I assign an OnClickListener
. In the onClick
method of the OnClickListener
, I want to launch a new activity. I get the exception:
Calling startActivity() from outside of an Activity context requires the
FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
如何获取ListView
(当前的Activity
)在其下工作的Context
?
How can I get the Context
that the ListView
(the current Activity
) is working under?
推荐答案
要么
- 通过适配器中的构造函数缓存 Context 对象,或
- 从你的角度来看.
或者作为最后的手段,
- 在您的意图中添加 - FLAG_ACTIVITY_NEW_TASK 标志:
_
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
编辑 - 我会避免设置标志,因为它会干扰事件和历史堆栈的正常流程.
Edit - i would avoid setting flags as it will interfere with normal flow of event and history stack.
这篇关于从 Activity 上下文外部调用 startActivity()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!