如何在适配器中启动 Activity? [英] How to start Activity in adapter?

查看:36
本文介绍了如何在适配器中启动 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?

谢谢.

推荐答案

只需将当前 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().

伪代码

public class MyAdapter extends Adapter {
     private Context context;

     public MyAdapter(Context context) {
          this.context = context;     
     }

     public View getView(...){
         View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 context.startActivity(...);
             }
         });
     }
}

这篇关于如何在适配器中启动 Activity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆