8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ViewModelとLiveDataを使ったDialogFragmentのコールバック

Posted at

2020年にもなっていまだにDialogFragmentのコールバック最適解がないのでGoogleは早くJetPackに作ってほしい

class MainActivity : AppCompatActivity() {

    private val viewModel: DialogViewModel<MainDialogResult> by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (savedInstanceState == null) {
            SampleDialogFragment().show(supportFragmentManager, "sample")
        }

        viewModel.result.observe(this) {
            when (it) {
                is MainDialogResult.Ok -> {
                    Log.i("result", it.message)
                }

                is MainDialogResult.Cancel -> {
                    Log.i("result", "cancel")
                }
            }
        }
    }
}

///////////////////// CallBack

sealed class MainDialogResult {
    data class Ok(val message: String) : MainDialogResult()
    object Cancel : MainDialogResult()
}

class DialogViewModel<T> : ViewModel() {
    val result: MutableLiveData<T> = MutableLiveData()
}

///////////////////// DialogFragment

class SampleDialogFragment : DialogFragment() {

    private val viewModel: DialogViewModel<MainDialogResult> by activityViewModels()

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return AlertDialog.Builder(requireContext())
            .setPositiveButton(android.R.string.ok) { _, _ ->
                val message = "OK!"
                viewModel.result.postValue(MainDialogResult.Ok(message))
            }
            .setNegativeButton(android.R.string.cancel) { _, _ ->
                viewModel.result.postValue(MainDialogResult.Cancel)
            }
            .create()
    }
}

これでActivity/Fragment共に画面回転のことも考慮してもちゃんと結果が受け取れるようになります。
しかしボイラープレートが多いですね...ほとんど再利用できる箇所がない

8
5
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
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?