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

时间:2019-02-27 20:20:20

标签: android kotlin android-dialogfragment android-dialog onitemclicklistener

有人知道我需要在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)!!
    }
}

1 个答案:

答案 0 :(得分:0)

要解决您的问题,您可以使用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)

但是您应该改为在创建ViewHolder时设置侦听器。在ViewHolder或onCreateViewHolder()的构造函数中。