Moh*_*Raj 2 android android-listview android-imageview
我有一个列表有一个图像button中的每个项目,当我一个图像上单击,我要开始另一个Activity用intent
以下是我的代码
我的问题是我无法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 !
}
});
Run Code Online (Sandbox Code Playgroud)
您应该在创建时将上下文传递给自定义适配器:
public class MyAdapter extends BaseAdapter {
private Context mContext;
public MyAdapter (Context ctx) {
mContext = ctx;
}
...
}
Run Code Online (Sandbox Code Playgroud)
并在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 !
}
});
Run Code Online (Sandbox Code Playgroud)
在Activity中创建适配器时,应将"this"作为参数传递:
mAdapter = new MyAdapter(this);
Run Code Online (Sandbox Code Playgroud)