Issue
i have this fragment dialog and i want to edit some host activity properties when he click on btnOk in line 26 can any one help me or give me another way to communicate between a dialog fragment and its host activity `
package com.exemple.tic_tac_toe
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.DialogFragment
import android.app.Activity
class restartDialog : DialogFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val layout : View = inflater.inflate(R.layout.exit_layout , container , false)
this.isCancelable = false
val btnOk : Button = layout.findViewById(R.id.btnYes)
val btnNo : Button = layout.findViewById(R.id.btnNO)
btnOk.setOnClickListener(){
dismiss()
/////here acces the host activity properties and change them
}
btnNo.setOnClickListener(){
dismiss()
}
return layout
}
}
`
Solution
I think the better approach would be to use an interface or a callback, rather than having the DialogFragment access the Activity properties.
You can create an interface:
interface DialogClickListener {
fun dialogOkClicked()
fun dialogCancelClicked()
}
Make the hosting Activity implement it:
class YourActivity: AppCompatActivity(), DialogClickListener {
override fun dialogOkClicked() {
}
override fun dialogCancelClicked() {
}
}
And in your DialogFragment, call those methods in case the Activity implements them:
btnOk.setOnClickListener(){
(activity as? DialogClickListener)?.dialogOkClicked()
dismiss()
}
btnNo.setOnClickListener(){
(activity as? DialogClickListener)?.dialogCancelClicked()
dismiss()
}
This would allow you to use this DialogFragment in other places and not inside a specific hosting Activity.
Answered By - gioravered
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.