Recycler View OnClick更改屏幕的背景图像

时间:2019-07-04 12:25:13

标签: java android

我有一个ArrayList,用于填充recyclerView。 当前,当用户单击recyclerView对象时,整个屏幕(而不是视图持有者)的背景会相应地更改颜色。

要实现此目的,我在recyclerView onClick侦听器中设置了switch语句。我想知道是否可以更动态地对此进行编程,因此在switch语句中不使用20种情况来更改背景img。我可以在ArrayList中添加背景img,然后在onBindViewHolder上调用它吗?到目前为止,我已经尝试过了:

数组列表:

  mMoodIcons.add(new MoodIcons(R.drawable.excited_icon,  
  R.mipmap.background_clouds_excited, 
  ContextCompat.getColor(getContext(), R.color.excited),"Excited"));

适配器:

public void onBindViewHolder(@NonNull MoodIconAdapter.MoodIconViewHolder holder, int position) {

    MoodIcons moodIcons = mMoodIcons.get(position);

    holder.moodImage.setImageResource(moodIcons.getMoodImage());
    holder.moodTitle.setText(moodIcons.getMoodName());
    holder.moodImage.setColorFilter(moodIcons.getColour());
     holder.mConstraintLayout.setBackgroundResource(moodIcons.getBackgroundImage());

}

/**
 * Method which makes our recycler list the same size as our arraylist of items.
 *
 * @return
 */
@Override
public int getItemCount() {
    return mMoodIcons.size();
}

public class MoodIconViewHolder extends RecyclerView.ViewHolder {

    /**
     * TextView variables containing objects from the XML file.
     */
    public TextView moodTitle;
    public ImageView moodImage;
    public ConstraintLayout mConstraintLayout;

    public MoodIconViewHolder(@NonNull View itemView) {
        super(itemView);

        // assign variables to objects in the XMl file.
        moodTitle = itemView.findViewById(R.id.recyclerMoodTitle);
        moodImage = itemView.findViewById(R.id.recyclerMoodImage);
        mConstraintLayout = itemView.findViewById(R.id.FragmentWorkoutMood2);

当前它在适配器中抛出空指针。

 java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.constraintlayout.widget.ConstraintLayout.setBackgroundResource(int)' on a null object reference
    at com.example.adapters.MoodIconAdapter.onBindViewHolder(MoodIconAdapter.java:98)
    at com.example.adapters.MoodIconAdapter.onBindViewHolder(MoodIconAdapter.java:19)

0 个答案:

没有答案