如何设置Alpha到recyclerview项(单击的除外)

时间:2019-02-06 18:29:07

标签: android android-recyclerview opacity onitemclicklistener

我有一个带有imageview和textview的recyclerview。我在其中填充了image和text。我使用了customadapter来实现recyclerview。一切正常,但现在我想要了

1)当我单击一个图像时,所有其他图像的alpha设置为0.5f

这是我的代码,仅阿尔法本身

public class CatAdapter extends RecyclerView.Adapter<CatAdapter.HeroViewHolder> {

  Context mCtx;
  List<CatModel> adsList;
  int selectedPosition=-1;

  public CatAdapter(Context mCtx, List<CatModel> heroList) {
    this.mCtx = mCtx;
    this.adsList = heroList;
  }

  @NonNull
  @Override
  public HeroViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(mCtx).inflate(R.layout.cat_recycler_layout, parent, false);

    return new HeroViewHolder(view);
  }

  @Override
  public void onBindViewHolder(@NonNull final HeroViewHolder holder, int position) {
    final CatModel hero = adsList.get(position);

    Glide.with(mCtx)
      .load(hero.getImageurl())
      .into(holder.imageView);

    holder.textView.setText(hero.getName());

    holder.imageView.setOnClickListener(new View.OnClickListener() {
        int button01pos = 0;
        @Override
        public void onClick(View view) {
          if (button01pos == 0) {
            holder.cross.setVisibility(View.VISIBLE);
            holder.imageView.setAlpha(1f);
            button01pos = 1;
          } else if (button01pos == 1) {
            holder.cross.setVisibility(View.GONE);
            holder.imageView.setAlpha(1f);
            button01pos = 0;
          }
        }
      });
  }

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

  class HeroViewHolder extends RecyclerView.ViewHolder {

    ImageView cross;
    CircleImageView imageView;
    TextView textView;

    public HeroViewHolder(View itemView) {
      super(itemView);

      imageView = itemView.findViewById(R.id.imageView);
      cross = itemView.findViewById(R.id.cross);
      textView = itemView.findViewById(R.id.textView);
    }
  }
}

2 个答案:

答案 0 :(得分:2)

尝试这种方式。

public class CatAdapter extends RecyclerView.Adapter<CatAdapter.HeroViewHolder> {

Context mCtx;
List<CatModel> adsList;
int selectedPosition=-1;
CatModel selectedItem = null;

@Override
public void onBindViewHolder(@NonNull final HeroViewHolder holder, int position) {
    ...
    holder.imageView.setAlpha(selectedItem == null || hero.equals(selectedItem) ? 1f : 0.5f);
    holder.imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            selectedItem = hero.equals(selectedItem) ? null : hero;
            ...
            notifyDataSetChanged();
        }
    });
}

...

答案 1 :(得分:0)

尝试这种方式

全球 selectedItem =-1

override fun onBindViewHolder(@NonNull final HeroViewHolder holder, int position) {
  if(position == selectedItem)holder.itemView.setAlpha(0.5f)

  holder.itemview.setOnClickListener{
     selectedItem = position
     notifyDataSetChanged()
  }
}