【问题标题】:How to set context in Alertdialog.builder() in adapter? [duplicate]如何在适配器的 Alertdialog.builder() 中设置上下文? [复制]
【发布时间】:2022-01-05 22:53:26
【问题描述】:

我想在我的适配器中为我的片段中的 recyclerview 实现 alertdialog。但是上下文有错误,如何在适配器中设置上下文?

 override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

        val currentitem = obatList[position]

        holder.namaObat.text = currentitem.namaObat
        holder.harga.text = currentitem.harga
        holder.keterangan.text = currentitem.keterangan
        holder.edit.setOnClickListener {
           showUpdateDialog()
        }

    }

    private fun showUpdateDialog() {
        val builder = AlertDialog.Builder()
    }
    
        override fun getItemCount(): Int {
    
            return obatList.size
        }
    
    
        class MyViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){
    
            val namaObat : TextView = itemView.findViewById(R.id.tvNamaObat)
            val harga : TextView = itemView.findViewById(R.id.tvHarga)
            val keterangan : TextView = itemView.findViewById(R.id.tvKeterangan)
            val edit : ImageButton = itemView.findViewById(R.id.ibEdit)
        }
    }

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    首先让你的函数接受一个你可以传递给你的构建器的上下文参数:

    private fun showUpdateDialog(context: Context) {
        val builder = AlertDialog.Builder(context)
            //...
    }
    

    然后您可以从绑定根或视图传递给您的点击监听器获取上下文:

        holder.edit.setOnClickListener { view ->
           showUpdateDialog(view.context)
        }
    

    或

        holder.edit.setOnClickListener {
           showUpdateDialog(it.context)
        }
    

    【讨论】:

      【解决方案2】:

      您所要做的就是获得作为类创建者的“上下文”。

      片段.kt

      YourAdapter(requireContext())
      

      YourAdapter.kt

      YourAdapter(context: Context){
      
          showUpdateDialog(){
              AlertDialog.Builder(context) 
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2020-08-25
        • 2011-11-21
        • 1970-01-01
        • 2016-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多