当我第一次点击按钮时,它运行正常。但是当我第二次点击它时,程序崩溃了:
指定的 child 已经有一个 parent 。您必须先对 child 的 parent 调用 removeView()。
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
val view1 = layoutInflater.inflate(R.layout.main_view1, null, false)
val btn1 = view1.findViewById<Button>(R.id.btn1)
val btn2 = view1.findViewById<Button>(R.id.btn2)
val btn3 = view1.findViewById<Button>(R.id.btn3)
btn1.setOnClickListener {
binding.textView.setTextColor(Color.RED)
}
btn2.setOnClickListener {
binding.textView.setTextColor(Color.BLUE)
}
btn3.setOnClickListener {
binding.textView.setTextColor(Color.GREEN)
}
binding.button.setOnClickListener {
AlertDialog.Builder(this)
.setTitle("Color")
.setView(view1)
.setCancelable(false)
.setPositiveButton("ok", DialogInterface.OnClickListener { _, _ ->
})
.create().show()
}
}
}
最佳答案
问题是您创建并持有对 view1
的引用一次:
val view1 = layoutInflater.inflate(R.layout.main_view1, null, false)
然后每次单击按钮时都尝试使用相同的 View :
binding.button.setOnClickListener {
AlertDialog.Builder(this)
.setTitle("Color")
.setView(view1)
.setCancelable(false)
.setPositiveButton("ok", DialogInterface.OnClickListener { _, _ ->
})
.create().show()
}
要解决它,您应该将设置代码移到按钮点击监听器中,以便为每个新的 AlertDialog
获得一个新的 view1
:
binding.button.setOnClickListener {
val view1 = layoutInflater.inflate(R.layout.main_view1, null, false)
val btn1 = view1.findViewById<Button>(R.id.btn1)
val btn2 = view1.findViewById<Button>(R.id.btn2)
val btn3 = view1.findViewById<Button>(R.id.btn3)
btn1.setOnClickListener {
binding.textView.setTextColor(Color.RED)
}
btn2.setOnClickListener {
binding.textView.setTextColor(Color.BLUE)
}
btn3.setOnClickListener {
binding.textView.setTextColor(Color.GREEN)
}
AlertDialog.Builder(this)
.setTitle("Color")
.setView(view1)
.setCancelable(false)
.setPositiveButton("ok", DialogInterface.OnClickListener { _, _ ->
})
.create().show()
}
关于android - "The specified child already has a parent. You must call removeView() on the child' s parent first”第二次创建AlertDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67913375/