overmind
overmind

Reputation: 477

Calling Parent Fragment function in DialogFragment [Kotlin]

I have a Fragment that calls a FragmentDialog via a floating action button using this code

class MainView : Fragment() {


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?

    ): View? {
        val v = inflater.inflate(R.layout.fragment_main_view, container, false)

        val fab1: FloatingActionButton = v.findViewById(R.id.fab1)
        fab1.setOnClickListener{
            val myDialog = DialogNewNote()
            myDialog.show(childFragmentManager, "")
        }
       return v
    }

    fun createNewNote(n: Note) {
        // perform something here
    }

}

Now in the DialogFragment, I want to call a function [createNewNote] from the calling Fragment in the code above. My question is, how can I create a reference to the Fragment from the FragmentDialog? I tried the code below, but it gives me an error. Please help

class DialogNewNote : DialogFragment() {
     override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

         val callingParent = activity as MainView
         callingParent!!.createNewNote(newNote)
         //----- more code here ----- //
    }
}

Upvotes: 0

Views: 691

Answers (1)

jefry jacky
jefry jacky

Reputation: 799

Your MainView is a fragment but you use activity, try to change it like below

if(parentFragment is MainView){
  (parentFragment as MainView).createNewNote(newNote)
}

Upvotes: 1

Related Questions