class CustomDialogFragment: DialogFragment(){
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val dialogview = LayoutInflater.from(requireActivity()).inflate(R.layout.customdialog, null)
val oktextview = dialogview.findViewById<TextView>(R.id.YES)
oktextview.setOnClickListener {
Log.i("tag","printif it works") //doesn't print
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val builder = AlertDialog.Builder(it)
val inflater = requireActivity().layoutInflater
builder.setView(inflater.inflate(R.layout.customdialog, null))
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
我正在使用自定义对话框,并想使用setOnClickListener
自定义对话框的组件。
我把它变成了onViewCreated
,但是不工作。
我如何在自定义对话框中实现setOnClickListener
为TextView
?
您正在为onViewCreated方法创建视图的不同实例。这意味着单击侦听器被设置在不显示给用户的视图上。
你可以这样做:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val builder = AlertDialog.Builder(it)
val inflater = requireActivity().layoutInflater
builder.setView(inflater.inflate(R.layout.customdialog, null))
val dialog = builder.create()
val oktextview = dialog.findViewById<TextView>(R.id.YES)
oktextview.setOnClickListener {
Log.i("tag","printif it works") //doesn't print
}
dialog
} ?: throw IllegalStateException("Activity cannot be null")
}
https://developer.android.com/reference/android/app/DialogFragment#alert-dialog
根据文档,你不应该实现onCreateView(),只使用onCreateDialog
在onCreateView()方法中调用它而不是onViewCreated()oktextview。setOnClickListener(视图→把());