I want to make static function with Alert dialog which return boolean value.
In C# it looks like:
DialogResult dialogResult = MessageBox.Show("Sure", "Some Title", MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
{
//do something
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
In Kotlin i have class with companion object
class Dialog {
companion object {
fun question(context: Context, title: String, message: String) {
AlertDialog.Builder(context).apply {
setIcon(R.drawable.ic_question)
setTitle(title)
setMessage(message)
setPositiveButton("YES", DialogInterface.OnClickListener { dialog, which ->
})
setNegativeButton("NO", DialogInterface.OnClickListener { dialog, which ->
})
}.show()
}
}
}
And i want to return Boolean result from question function.
I want to use this function in my activity like this:
if(Dialog.question(this,"Title", "Message")) {
//something
} else {
//something
}
Is it possible?
Yes it is possible.
What you need:
This is the implementation in my code (tested and working)
Implementation:
Extend your Dialog.kt class with DialogFragment, adapt your code to this and create the interface
class Dialog: DialogFragment() {
interface InputListener {
fun sendBoolean(value: Boolean)
}
...
}
In the positive / negative listeners lambdas, init your interface and send the boolean
val inputListener = activity as InputListener
inputListener.sendInput(YOUR_VALUE)
dialog?.dismiss()
Go to your activity and extend it with your interface
class MainActivity: AppCompatActivity(), Dialog.InputListener {
...
}
And now finally, override the interface in the activity to run the code you need
override fun sendInput(value: Boolean) {
if (value) {
// Positive - true
} else {
// Negative - false
}
}
Please let me know if this solved your problem, if not, try updating your question with what's wrong and I'll help you by updating my answer, happy coding!