为每个RecyclerView项目生成ImageView,每个项目都有不同数量的ImageView。我已经生成了ImageViews,但现在我必须为每个项目中生成的每个图像设置 OnClick 。我不知道如何做到这一点。任何帮助将不胜感激。
ImageView在适配器中生成代码:
@Override
public void onBindViewHolder(ListHolder holder, final int position) {
holder.name.setText(names[position]);
// BELOW CODE IS THERE TO DYNAMICALLY ADD IMAGES
LinearLayout ll = new LinearLayout(c);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
ll.setLayoutParams(params);
for(int i=0;i<num[position];i++)
{
holder.image = new ImageView(c);
holder.image.setLayoutParams(new ViewGroup.LayoutParams(200,
200));
holder.image.setImageResource(R.mipmap.ic_launcher);
ll.addView(holder.image);
}
holder.horizontalScrollView.addView(ll);
}
上面的代码在适配器内部,我很乐意为您提供所有代码以备不时之需。请告诉我如何处理生成的这些图像的点击事件。感谢。
答案 0 :(得分:1)
您可以在holder.image
对象上执行此操作。以下是基于您的代码的示例:
for(int i=0;i<num[position];i++)
{
holder.image = new ImageView(c);
holder.image.setLayoutParams(new ViewGroup.LayoutParams(200,
200));
holder.image.setImageResource(R.mipmap.ic_launcher);
//setting the onClickListener to image
holder.image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//image clicked, do stuff
}
});
ll.addView(holder.image);
}
我希望这会有所帮助。试一试,让我知道。
答案 1 :(得分:1)
@Override
public void onBindViewHolder(ListHolder holder, final int position) {
holder.name.setText(names[position]);
// BELOW CODE IS THERE TO DYNAMICALLY ADD IMAGES
LinearLayout ll = new LinearLayout(c);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
ll.setLayoutParams(params);
for(int i=0;i<num[position];i++)
{
ImageView img = new ImageView(c);
img.setLayoutParams(new ViewGroup.LayoutParams(200,
200));
img.setImageResource(R.mipmap.ic_launcher);
img.setId(i);
ll.addView(img);
img.setOnClickListner(OnClickListener() {
@Override
public void onClick(View v) {
}
}));
}
holder.horizontalScrollView.addView(ll);
}