13
8

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 5 years have passed since last update.

Navigationを使ってDialogFragmentを表示する

Last updated at Posted at 2019-09-10

navigation#2.1.0-alpha03 から DialogFragmentがサポートされました。
https://developer.android.com/jetpack/androidx/releases/navigation#2.1.0-alpha03

<dialog>としてnavigationのxmlには定義する

navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools" android:id="@+id/top"
            app:startDestination="@id/TopFragment">
    略...
    <dialog
        android:id="@+id/datePickerDialogFragment"
        android:name="com.example.DatePickerDialogFragment"
        android:label="DatePickerDialogFragment" >
    </dialog>
</navigation>

ダイアログを表示したい時は通常のnavigationと同様

val action = TopFragmentDirections.actionTopFragmentToDatePickerDialogFragment()
findNavController().navigate(action)

ダイアログの結果の反映や値の受け渡しにはViewModelを使えば良い。

DatePickerDialogFragment.kt
class DatePickerDialogFragment : DialogFragment(), AnkoLogger {
    lateinit var viewModel: TopViewModel
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return DatePickerDialog(
            requireContext(),
            DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
                viewModel.onDateSet(year,month,dayOfMonth)
            },
            viewModel.year,
            viewModel.month,
            viewModel.dayOfMonth)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProviders.of(this, ViewModelFactory).get(TopViewModel::class.java)
    }
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?