Skip to content

Instantly share code, notes, and snippets.

@PaulKlauser
Created January 30, 2023 14:27
Show Gist options
  • Save PaulKlauser/4fa374a9249de372b71676622923b214 to your computer and use it in GitHub Desktop.
Save PaulKlauser/4fa374a9249de372b71676622923b214 to your computer and use it in GitHub Desktop.
DialogFragment that obeys display state
class MainActivity : AppCompatActivity() {
private val vm by viewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
vm.dialogShown.collect { shown ->
MyDialogFragment.bind(supportFragmentManager, shown)
}
}
}
}
}
class MyDialogFragment : DialogFragment() {
companion object {
private const val TAG = "MyDialog"
fun bind(fragmentManager: FragmentManager, shown: Boolean) {
if (shown) {
// Prevent showing duplicate Fragments with the same tag over top each other
if (fragmentManager.findFragmentByTag(TAG) == null) {
MyDialogFragment().show(fragmentManager, TAG)
}
} else {
(fragmentManager.findFragmentByTag(TAG) as? MyDialogFragment)?.dismiss()
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(requireContext())
.setTitle("This is the Title!")
.setMessage("This is the Message!")
.setPositiveButton("OK") { _, _ -> dismiss() }
.show()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment