0

I'm using Android's Navigation component and I'm wondering how to setup AlertDialog from a fragment with a click listener.

MyFragment

fun MyFragment : Fragment(), MyAlertDailog.MyAlertDialogListener {
     ...

    override fun onDialogPostiveCLick(dialog: DialogFragment) {
        Log.i(TAG, "Listener returns a postive click")
    }

     fun launchMyAlertDialog() {
          // Here I would typically call setTargetFragment() and then show the dialog. 
          // but findnavcontroller doesn't have setTargetFragment()
         findNavController.navigate(MyFragmentDirection.actionMyFragmentToMyAlertDialog())
     }
}

MyAlertDialog

class MyAlertDialog : DialogFragment() {

    ... 

    internal lateinit var listener: MyAlertDialogListener

    interface MyAlertDialogListener{
        fun onDialogPostiveCLick(dialog: DialogFragment)
    }

    override fun onCreateDialog(savdInstanceState: Bundle?): Dialog {
        return activity?.let {
            val builder = AlertDialog.Builder(it) 
            builder.setMessage("My Dialog message")
                .setPositiveButton("Positive", DialogInterface.OnClickListener {
                    listener = targetFragment as MyAlertDialogListener                    
                    listener.onDialogPositiveClick(this)
                }
            ...
        }
    }
}

This currently receives a null point exception when initializing the listener in MyAlertDialog.

Shawn
  • 1,222
  • 1
  • 18
  • 41

1 Answers1

0

To use targetFragment, you have to set it first as you commented, unfortunately jetpack navigation does not do this for you (hence the null pointer exception). Check out this thread for alternative solution: https://stackoverflow.com/a/50752558/12321475

What I can offer you is an alternative. If the use-case is as simple as displaying a dialog above current fragment, then do:

import androidx.appcompat.app.AlertDialog
...

class MyFragment : Fragment() {
     ...

    fun onDialogPostiveCLick() {
        Log.i(TAG, "Listener returns a postive click")
    }

     fun launchMyAlertDialog() {
          AlertDialog.Builder(activity)
            .setMessage("My Dialog message")
            .setPositiveButton("Positive") { _, _ -> onDialogPostiveCLick() }
            .setCancellable(false)
            .create().show()
     }
}
Dat Pham Tat
  • 1,433
  • 7
  • 9