Home > Blockchain >  How to use click listener in custom dialog fragment?
How to use click listener in custom dialog fragment?

Time:09-27

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")
  }
}

I'm using custom dialog, and wanna use setOnClickListener for components of custom dialog.

I did it into onViewCreated, but doesn't work.

How can I implement setOnClickListener for TextView in custom dialog please?

CodePudding user response:

You are creating a different instance of the view for the onViewCreated method. This means the clicks listener is being set on a view that is not shown to the user.

You can achieve what you want doing the following:

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")
}

CodePudding user response:

https://developer.android.com/reference/android/app/DialogFragment#alert-dialog


Based on the documentation you should not implement onCreateView() Just use onCreateDialog

  • Related