我有一个列表,每个项目中都有一个图像 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/