如何在点击时创建一个按钮,背景颜色会改变

huangapple go评论103阅读模式
英文:

How to create a button on click the background color changes

问题

我尝试使用按钮和点击事件来更改背景颜色。此外,我不知道如何在点击时添加复选标志,以及如何在点击下一个按钮时将其恢复为默认状态。

英文:

enter image description here
Check image

I tried using button and on click event to change the background color. Also I don't know how to add the check icon on click and also how to return it to default state clicking the next button

答案1

得分: 2

将索引初始设置为-1并且当你点击该项时它会改变特定项的颜色

    index = -1;

    public void onBindViewHolder(final ViewHolder holder, final int position) {

        holder.view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index = position;
                notifyDataSetChanged();
            }
        });
        if (index == position) {
            holder.view.setBackgroundColor(Color.parseColor("#567845"));
            holder.tv1.setTextColor(Color.parseColor("#ffffff"));
        } else {
            holder.view.setBackgroundColor(Color.parseColor("#ffffff"));
            holder.tv1.setTextColor(Color.parseColor("#000000"));
        }

    }
英文:

Set index to -1 initially and when you click the item it will change color of particular item

index=-1;

public void onBindViewHolder(final ViewHolder holder, final int position) {
      

        holder.view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index=position;
                notifyDataSetChanged();
            }
        });
        if(index==position){
            holder.view.setBackgroundColor(Color.parseColor("#567845"));
            holder.tv1.setTextColor(Color.parseColor("#ffffff"));
        }
        else
        {
            holder.view.setBackgroundColor(Color.parseColor("#ffffff"));
            holder.tv1.setTextColor(Color.parseColor("#000000"));
        }

    }

huangapple
  • 本文由 发表于 2023年3月7日 19:48:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661603.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定