[英]How to use click listener in custom dialog fragment?
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
中做了它,但沒有用。
請問如何在自定義對話框中為TextView
實現setOnClickListener
?
您正在為 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(view -> dismiss());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.