android 如何在自定义对话框布局中使用视图绑定?

xoefb8l8  于 2023-10-14  发布在  Android
关注(0)|答案(5)|浏览(117)

我在自定义对话框布局中实现视图绑定时遇到了问题。有可能吗?

private fun showCustomDialog(title: String) {
    val dialog = Dialog(activity)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(false)

    dialog.setContentView(R.layout.custom_layout)

    val body = dialog.findViewById(R.id.body) as TextView
    body.text = title

    val noBtn = dialog.findViewById(R.id.noBtn) as TextView
    yesBtn.setOnClickListener {
        dialog.dismiss()
    }

    val yesBtn = dialog.findViewById(R.id.yesBtn) as Button
    noBtn.setOnClickListener { dialog.dismiss() }
    dialog.show()

}
cbeh67ev

cbeh67ev1#

这是可能的。

CustomDialogBinding binding = CustomDialogBinding 
          .inflate(LayoutInflater.from(getContext()));
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setView(binding.getRoot());

其中CustomDialogBinding是自定义布局的视图绑定文件的名称
Kotlin

val bind :CustomDialogBinding = CustomDialogBinding .inflate(inflater)
dialog.setContentView(bind.root)
ccgok5k5

ccgok5k52#

验证码:

val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val binding = CustomDialogLayoutBinding.inflate(inflater)
dialog.setContentView(binding.root)
abithluo

abithluo3#

范例:

val dialogBinding = DialogCustomBinding.inflate(layoutInflater)
dialog.setView(dialogBinding.root)
pepwfjgg

pepwfjgg4#

与第一个答案类似,包括一些额外的行。假设您的绑定是DialogReviewBinding

val inflater = activity.layoutInflater
val dialogBinding = DialogReviewBinding.inflate(inflater)
val dialog = AlertDialog.Builder(activity).create()
dialog.setView(dialogBinding.root)
dialog.show()

它被一个activity?.let { activity -> }块包围着

vfhzx4xs

vfhzx4xs5#

验证码:

val winnerDBinding =WinnerDialougeBinding.inflate(layoutInflater)
 val dialog = Dialog(this);
 dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
 dialog.setCancelable(false)
 dialog.setContentView(winnerDBinding.root)

 winnerDBinding.btnPlayAgain.setOnClickListener {
    val intent = Intent(this,MainActivity::class.java)
    finish()
    startActivity(intent)
 }
 dialog.show()

相关问题