如何在适配器中启动Activity?
我有一个带有自定义适配器的 ListActivity,并且在每个视图内,它可能有一些按钮,我需要在其中实现 OnClickListener
。我需要在适配器中实现 OnClickListener
。但是,我不知道如何调用 startActivity()
或 setResult()
等函数。由于适配器没有扩展到 Activity。
那么解决这个问题的最佳方法是什么?
谢谢。
I have a ListActivity with my customized adapter and inside each of the view, it may have some buttons, in which I need to implement OnClickListener
. I need to implement the OnClickListener
in the adapter. However, I don't know how to call the function like startActivity()
or setResult()
. Since the adapter doesn't extend to Activity.
So what is the best way to solve this problem?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
只需将当前 Context 传递给 Adapter 构造函数并将其存储为字段即可。然后在 onClick 中,您可以使用该上下文来调用 startActivity()。
伪代码
Just pass in the current Context to the Adapter constructor and store it as a field. Then inside the onClick you can use that context to call startActivity().
pseudo-code
实现
onClickListener
时,可以使用v.getContext.startActivity
。When implementing the
onClickListener
, you can usev.getContext.startActivity
.对于较新版本的 sdk,您必须设置标志活动任务。
For newer versions of sdk you have to set flag activity task.
在采用者按钮 onClickListener 中启动活动的简单方法:
Simple way to start activity in Adopter's button onClickListener:
从适配器到活动的回调可以使用接口形式注册侦听器来完成:
创建一个接口:
在适配器中让我们说 MyAdapter:
//在需要触发监听器的地方执行此操作
我
callback from adapter to activity can be done using registering listener in form of interface:
Make an interface:
In Adapter Let's Say MyAdapter:
//do this where u need to fire listener
l
view - 图像的
public void onClick(View view)
OnClick
。view -
public void onClick(View view)
OnClick
of image.第一个解决方案:
您可以像这样调用适配器内的启动活动:
第二个解决方案:
您可以从
中调用按钮的
类。请按照以下步骤操作:onClickListener
>YourAdapter创建一个如下所示的界面:
然后在您的适配器内:
启动您的适配器的位置将如下所示:
这个 链接 对您有用。
First Solution:
You can call start activity inside your adapter like this:
Second Solution:
You can call
onClickListener
of your button out of theYourAdapter
class. Follow these steps:Craete an interface like this:
Then inside your adapter:
And where you initiate yourAdapter will be like this:
This link can be useful for you.
如果您想重定向到 url 而不是来自适配器类的 Activity,则传递 startactivity 的上下文。
If you want to redirect on url instead of activity from your adapter class then pass context of with startactivity.