如何在不创建其他类的情况下访问对话框的视图



有人知道我需要在recyclerview适配器中使用哪个上下文(如果那样),而无需创建新的DialogFragment类?将来,我将需要访问和使用对话框的视图。先前使用的代码是我过去用于RecyClerview适配器的方法,但是现在需要使用自定义视图时它是多余的。

未解决的参考:'layoutinflater'

先前使用的代码

    holder.myButton.setOnClickListener {
        val builder = android.app.AlertDialog.Builder(holder.itemView.context)
        builder.setIconAttribute(R.attr.ivInfo)
        builder.setTitle(R.string.dialog_title)
        builder.setMessage(R.string.dialog_message)
        builder.setView(R.layout.custom_view)
        builder.setPositiveButton(android.R.string.ok){ dialog, _ -> dialog.dismiss() }
        val dialog: android.app.AlertDialog = builder.create()
        dialog.show()
    }

当前代码

class MyRVAdapter() : RecyclerView.Adapter<MyRVAdapter.ViewHolder>() {
    override fun getItemCount(): Int {
        return myList.size
    }
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.myButton.setOnClickListener {
            customView = holder.itemView.context.this.layoutInflater.inflate(R.layout.fragment_dialog, null)
                val builder = AlertDialog.Builder(holder.itemView.context)
                 builder.setIconAttribute(R.attr.imgNight)
                 builder.setTitle(R.string.dialog_title)
                 builder.setView(customView)
                 builder.setPositiveButton(android.R.string.ok){ dialog, _ -> dialog.dismiss() }
                 builder.show()
                tabLayout = customView.findViewById(R.id.mTabLayout)
                viewPager = customView.findViewById(R.id.mViewPager)
                val adapter = TabbedDialogAdapter(childFragmentManager)
                adapter.addFragment("Tab A", TabbedDialogFragment.createInstance("Description A"))
                adapter.addFragment("Tab B", TabbedDialogFragment.createInstance("Description B"))
                adapter.addFragment("Tab C", TabbedDialogFragment.createInstance("Description C"))
                customView.mViewPager.adapter = adapter
                customView.mTabLayout.setupWithViewPager(customView.mViewPager)
            }
        }
     }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.my_cv, parent, false)
        return ViewHolder(v)
    }
    class ViewHolder (itemView : View):RecyclerView.ViewHolder(itemView) {
        val myButton = itemView.findViewById<Button>(R.id.btn_A)!!
    }
}

要解决您的问题,您可以使用View.inflate()

更改此行:

customView = holder.itemView.context.this.layoutInflater.inflate(R.layout.fragment_dialog, null)

customView = View.inflate(holder.itemView.context, R.layout.fragment_dialog, null)

但是,您应该将听众设置为创建视图持有人。在View Holder或onCreateViewHolder()的构造函数中。

相关内容

  • 没有找到相关文章

最新更新