Last active
February 13, 2025 11:29
-
-
Save ch8n/319a60251885ad538f149e9a1037f7b9 to your computer and use it in GitHub Desktop.
Android alert dialog kotlin Extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Utils - Declaration | |
object PromptUtils { | |
fun alertDialog(context: Context, @StyleRes style: Int, dialogBuilder: AlertDialog.Builder.() -> Unit): Dialog { | |
val builder = AlertDialog.Builder(context, style).also { | |
it.setCancelable(false) | |
it.dialogBuilder() | |
} | |
return builder.create() | |
} | |
fun AlertDialog.Builder.negativeButton(text: String = "Dismiss", handleClick: (dialogInterface: DialogInterface) -> Unit = {}) { | |
this.setPositiveButton(text) { dialogInterface, which -> handleClick(dialogInterface) } | |
} | |
fun AlertDialog.Builder.positiveButton(text: String = "Continue", handleClick: (dialogInterface: DialogInterface) -> Unit = {}) { | |
this.setNegativeButton(text) { dialogInterface, which -> handleClick(dialogInterface) } | |
} | |
} | |
//Usage | |
PromptUtils.alertDialog(this, R.style.AlertDialog_AppCompat_Light) { | |
setTitle("Permission") | |
setMessage("Storeage read and write permission?") | |
positiveButton(){ | |
//do positive actions | |
it.dismiss() | |
} | |
negativeButton(){ | |
//do negative actions | |
it.dismiss() | |
} | |
} | |
//My Version of creating a Dialog with "action" lambda
Declaration
fun Context.createDialog(
@LayoutRes layout: Int,
@StyleRes style: Int,
isCancelable: Boolean = false,
action: Dialog.() -> Unit,
) {
val dialog = Dialog(this, style).apply {
setContentView(layout)
run { action.invoke(this) }
setCancelable(isCancelable)
create()
}
if (!dialog.isShowing) {
dialog.show()
}
}
Example Usage
createDialog(R.layout.reset_to_defaults_dialog,
R.style.Style_Dialog_Rounded_Corner_85,
isCancelable = false,
shouldApplyGravity = false,
action = {
val btnYes= findViewById<TextView>(R.id.btnYes)
val btnNo= findViewById<TextView>(R.id.btnNo)
btnYes.setOnClickListener{
}
btnNo.setOnClickListener{
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can we get textview or spinner value in
// Usage
alert {
setTitle("Confirm")
setMessage("Are you sure you want to delete this item?")
positiveButton { textview or spinner value here }
negativeButton { //do something }
}