RecyclerView-根据标志实现黑白项目图像

时间:2019-07-13 18:24:48

标签: java android android-recyclerview

我尝试创建一个显示图像的RecyclerView。我想实现一个功能,如果某些变量状态为“ CLOSE”,则使图像项为B&W,否则将其保留为RGB。

我有一个名为Player的对象。 Player包含:int idint imgAdrsString status

我将所有玩家图像地址RecyclerView的数组和所有玩家状态allPlayers的数组传递给mStatus

由于我试图避免每个项目都有2张图片(一个RGB和第二个BW)-我尝试在ViewHolder构造函数初始化期间对ImageView个项目应用BW过滤器。

但是status变量不会传递到ViewHolderstatusnull),并且仅对RecyclerViewAdapter可见。

有人可以帮我解决这个问题吗?

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    private ArrayList<Integer> allPlayers = new ArrayList<>();
    private ArrayList<String> mStatus = new ArrayList<>();
    private Context mContext;

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

    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lay_players_item_list, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {   
        Glide.with(mContext)
                .asBitmap()
                .load(allPlayers.get(position))
                .into(holder.image);

        holder.status = mStatus.get(position);
        holder.parentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(mContext, "(:", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() { //How many items are in the list
        return allPlayers.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
            ImageView image;
        RelativeLayout parentLayout;
        String status;

        public ViewHolder(View itemView) {
            super(itemView);
            image = itemView.findViewById(R.id.image);
            parentLayout = itemView.findViewById(R.id.parent_layout);

            if (status.equals("CLOSE")) {
                ColorMatrix matrix = new ColorMatrix();
                matrix.setSaturation(0);

                ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
                image.setColorFilter(filter);

            }
        }
    }

1 个答案:

答案 0 :(得分:1)

将此代码添加到onBindViewHolder

        if (mStatus.get(position).equals("CLOSE")) {
            ColorMatrix matrix = new ColorMatrix();
            matrix.setSaturation(0);

            ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
            holder.image.setColorFilter(filter);

        }

您只能在onBindViewHolder方法内编辑任何视图。 Viewholder就像只持有您的视图的持有人。

让我知道这是否可以解决您的问题吗?