安卓点击设置imageview

时间:2018-12-02 06:40:37

标签: android android-recyclerview onclick imageview

因此,我有一个使用recyclerview和cardview的android项目,在其中单击卡即可设置背景imageview。这是我的代码:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.Viewholder> {
private ArrayList <Integer> mImages = new ArrayList<>();

public RecyclerViewAdapter( Context mContext, ArrayList<Integer> mImages) {
    this.mImages = mImages;
}

@NonNull
@Override
public Viewholder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemlist,viewGroup,false);

    return new Viewholder(view);
}

@Override
public void onBindViewHolder(@NonNull final Viewholder viewholder, int i) {
    viewholder.img.setImageResource(mImages.get(i));
}

@Override
public int getItemCount() {
    return mImages.size();
}

public class Viewholder extends RecyclerView.ViewHolder implements View.OnClickListener{

    ImageView img;
    ImageView imv;

    public Viewholder(@NonNull View itemView) {
        super(itemView);
        img = itemView.findViewById(R.id.imgview);
        imv = itemView.findViewById(R.id.imageView4);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Log.d("TEST", "Clicked");
        int position = getLayoutPosition();
        imv.setImageResource(R.drawable.vehicles);

    }
}
}

但是在点击时不起作用,并且应用程序崩溃了。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:0)

您必须将itemView定义为可点击才能接收点击事件。

android:clickable="true"

答案 1 :(得分:0)

请尝试将onClickListener移至onBindViewHolder

@Override
public void onBindViewHolder(@NonNull final Viewholder viewholder, int i) {
    viewholder.img.setImageResource(mImages.get(i));
    viewholder.img.setOnClickListener(v -> {
      // your code
    });

}

答案 2 :(得分:0)

请尝试

 itemView.setOnClickListener(new View.OnClickListener{
     @Override
     public void onClick(View view){
         //your code
     }
 });