0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Androidでダイアログが複数表示されるのを防ぐ

0
Posted at

通信処理など並列処理を行なっている時にエラーが発生した場合、エラー表示を行いますが一度だけで良いです。AndroidのDialogを同時に表示させない方法をメモします。

ダイアログ表示中のフラグを持つ

シンプルな方法は管理するフラグを用意することです。こちらは実装が分かりやすいですが、フラグの管理とダイアログ状態管理を気にしないといけないです。

object ErrorDialogManager {

    private var isShowing = false

    fun show(
        fragmentManager: FragmentManager,
        message: String
    ) {
        if (isShowing) return

        isShowing = true

        ErrorDialogFragment.newInstance(message)
            .apply {
                onDismissListener = {
                    isShowing = false
                }
            }
            .show(fragmentManager, "error")
    }
}
override fun onDismiss(dialog: DialogInterface) {
    super.onDismiss(dialog)

    onDismissListener?.invoke() // 閉じたタイミングでフラグを戻す
}

呼び出し側

ErrorDialogManager.show(supportFragmentManager, "通信エラーが発生しました")

FragmentManagerで表示中か確認する

FragmentManagerからタグを使って既に表示されているかを確認します。後から呼ばれても、既に同じタグのダイアログが存在していれば、新たなダイアログは表示されません。

companion object {
    const val TAG = "error_dialog"
}

if (supportFragmentManager.findFragmentByTag(tag) == null) {
    ErrorDialogFragment()
        .show(supportFragmentManager, tag)
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?