Created
November 7, 2020 13:06
-
-
Save Akhu/03ca557676b9e59eb37c5132947eb737 to your computer and use it in GitHub Desktop.
A simple Dialog Fragment in Kotlin
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
| import android.app.AlertDialog | |
| import android.app.Dialog | |
| import android.os.Bundle | |
| import android.text.InputType | |
| import android.widget.EditText | |
| import androidx.fragment.app.DialogFragment | |
| class RegisterDialogFragment : DialogFragment() { | |
| var onPositiveClick: ((userName: String) -> Unit)? = null | |
| var onNegativeClick: (() -> Unit)? = null | |
| override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { | |
| val editText = EditText(context) | |
| editText.inputType = InputType.TYPE_CLASS_TEXT | |
| return with(AlertDialog.Builder(context)) { | |
| setView(editText) | |
| setTitle("Create a new Profile") | |
| setMessage("Enter an astronaut Pseudo") | |
| setPositiveButton("Register") { _, _ -> onPositiveClick?.invoke(editText.text.toString()) } | |
| setNegativeButton("Cancel") { dialog, _ -> | |
| dialog.cancel() | |
| onNegativeClick?.invoke() } | |
| create() | |
| } | |
| } | |
| } | |
| //Usage | |
| // Usage | |
| fun showDialog() { | |
| val dialog = RegisterDialogFragment() | |
| dialog.onPositiveClick = { | |
| val myEditTextValue = it | |
| } | |
| activity?.supportFragmentManager?.let { dialog.show(it, "RegisterDialog") } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment