【问题标题】:Toggle background for a button programmitacly in android kotlin在 android kotlin 中以编程方式切换按钮的背景
【发布时间】:2022-11-02 00:18:46
【问题描述】:
class Split_recycler_adapter (var arrayList: ArrayList<Split_recycler_model>) :
    RecyclerView.Adapter<Split_recycler_adapter.Viewholder>()  {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Viewholder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.changesplit_recycler_item,parent,false)
        return Viewholder(v)
    }

    override fun onBindViewHolder(holder: Viewholder, position: Int) {
        val split_modal = arrayList[position]
        var checked = true

        Log.e("position_outside_loop->","$position")

        holder.split_text.text = split_modal.getText()
        holder.split_text.setOnClickListener{
                    if(checked){
                        Log.e("check->","Working")
                        holder.split_text.setBackgroundResource(R.drawable.green_button_gradient)
                        holder.split_text.setTextColor(Color.parseColor("#454546"))
                        checked = false
                    }else{
                        holder.split_text.setBackgroundResource(R.drawable.dropdown_gradient)
                        holder.split_text.setTextColor(Color.parseColor("#A4A4A4"))
                        checked = true
                    }


        }

    }

    override fun getItemCount(): Int {
        return arrayList.size
    }
    class Viewholder(Itemview: View) : RecyclerView.ViewHolder(Itemview) {

        val split_text : TextView = Itemview.findViewById(R.id.split_text)

    }

}

此代码可帮助我在单击时更改按钮的背景,并在再单击一次时恢复背景,但这不是我想要的确切内容,我需要在单击时切换背景,当单击完成时它应该想要要删除另一个按钮的背景,一次只能突出显示一个按钮,如果有人知道解决方案,请帮助我

【问题讨论】:

    标签: android kotlin toggle


    【解决方案1】:

    你不能这样做。

    您已在活页夹中添加了一个单击侦听器,并为主要位于该持有人位置的该项目执行了checked 逻辑。它不会影响其他位置的其他项目。因此,要更新其他职位的状态,您必须通过在 Split_recycler_model 类中添加 isChecked 变量来管理每个项目的状态。

        class Split_recycler_model {
            var isChecked : Boolean = false
        }
    

    在视图的 onClick 中,为特定的 adapterPosition 更新您的列表项。

    更新了点击操作,

    holder.split_text.setOnClickListener{
        checkItem(adapterPosition)
    }
    
    fun checkItem(adapterPosition:Int) {
      arrayList.forEachIndexed{index,item ->
          item.apply{
            isChecked = (index == adapterPosition)
          }
      }
    
      /**
          Here you can manually calculate the changes
          to update adapter to improve performance. 
      */
      notifyDataSetChanged()
    }
    

    【讨论】:

    • 你能解释清楚吗
    猜你喜欢
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 2020-05-15
    • 2013-01-26
    • 1970-01-01
    • 2011-09-27
    • 2017-11-02
    • 2013-09-12
    相关资源
    最近更新 更多