Skip to content

Instantly share code, notes, and snippets.

@pbochenski
Created July 2, 2020 08:52
Show Gist options
  • Save pbochenski/58302cacc994e5df71f6c0cafc0c390f to your computer and use it in GitHub Desktop.
Save pbochenski/58302cacc994e5df71f6c0cafc0c390f to your computer and use it in GitHub Desktop.
import android.os.Bundle
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import com.github.githubsearch.R
class OkDialog : DialogFragment() {
companion object {
private const val KEY_TITLE = "key:title"
private const val KEY_MESSAGE = "key:message"
fun newInstance(
@StringRes title: Int,
message: String
) = OkDialog().apply {
arguments = bundleOf(
KEY_TITLE to title,
KEY_MESSAGE to message
)
}
}
private val title by lazy { requireArguments().getInt(KEY_TITLE) }
private val message by lazy { requireArguments().getString(KEY_MESSAGE) }
override fun onCreateDialog(savedInstanceState: Bundle?): AlertDialog =
AlertDialog.Builder(requireContext())
.setTitle(title)
.setMessage(message)
.setNeutralButton(R.string.ok) { _, _ -> }
.create()
fun showOnce(fragmentManager: FragmentManager, tag: String) {
if (isStateSaved || fragmentManager.isStateSaved) return
with(fragmentManager) {
val oldDialog = findFragmentByTag(tag)
beginTransaction()
.apply { if (oldDialog != null) remove(oldDialog) }
.add(this@OkDialog, tag)
.commit()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment