android - 如何通过单击 ListView 的图像按钮来启动 Activity ?

标签 android android-listview android-imageview

我有一个列表,每个项目中都有一个图像 button 当我单击图像时,我必须使用 intent 启动另一个 Activity

以下是我的代码

我的问题是我无法从自定义适配器调用 startActivity()! !

在自定义适配器的 getView()

  holder.profilePicture.setOnClickListener(new OnClickListener() 
       { 
           public void onClick(View v) 
           {
               Log.d("OnImageButton","Clicked");
               Intent zoom=new Intent(AllProfile.getAppContext(), ImageZoom.class);
               int imageID=holder.profilePicture.getId();
               zoom.putExtra("ImageId", imageID);
               startActivity(zoom)  ; //This line raises error !      
                           }


       });

最佳答案

您应该在创建自定义适配器时将上下文传递给它:

public class MyAdapter extends BaseAdapter {
    private Context mContext;

    public MyAdapter (Context ctx) {
        mContext = ctx;
    }

    ...
}

然后在 getView 中使用该上下文启动 Activity:

 holder.profilePicture.setOnClickListener(new OnClickListener() 
   { 
       public void onClick(View v) 
       {
           Log.d("OnImageButton","Clicked");
           Intent zoom=new Intent(mContext, ImageZoom.class);
           int imageID=holder.profilePicture.getId();
           zoom.putExtra("ImageId", imageID);
           mContext.startActivity(zoom)  ; //This line raises error !      
                       }


   });

当您在 Activity 中创建适配器时,您应该将“this”作为参数传递:

 mAdapter = new MyAdapter(this);

关于android - 如何通过单击 ListView 的图像按钮来启动 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17190268/

相关文章:

android - 使多个卡片 View 在水平回收 View 中可见

android - 单击CheckBox时如何获取ListView中的项目

android - 用于在 Android 应用程序中显示图片 [不是图标] 的 PNG 与 JPG

imageview - 在 ConstraintLayout 中有一个具有相同宽度和高度的 ImageView

android - 将蓝牙代码移至新 Activity ,现在在激活时崩溃

java - 用gradle文件同步项目时出现问题

带有客户端证书的 Android 2.2 SSL Bug?

java - 使用自定义适配器将 HashMap 数据映射到 listView

android - 在 android ListView 中滚动时出现滞后

android - ImageView 在方向更改期间不保持恒定高度