Created
January 30, 2023 14:27
-
-
Save PaulKlauser/4fa374a9249de372b71676622923b214 to your computer and use it in GitHub Desktop.
DialogFragment that obeys display state
This file contains 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
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) | |
} | |
} | |
} | |
} | |
} |
This file contains 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
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