使用导航组件显示日期选择器对话框片段时出现问题

Trouble showing datepicker dialog fragment using Navigation component

我正在尝试使用导航组件来显示日期选择器对话框片段。我收到以下错误:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

这是我的日期选择器class

class DatePickerFragment : DialogFragment(), DatePickerDialog.OnDateSetListener {

var datePickerListener: DatePickerFragmentListener? = null

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    // Use the current date as the default date in the picker
    val c = Calendar.getInstance()
    val year = c.get(Calendar.YEAR)
    val month = c.get(Calendar.MONTH)
    val day = c.get(Calendar.DAY_OF_MONTH)

    // Create a new instance of DatePickerDialog and return it
    return DatePickerDialog(VitrixDataCollectionApp.context, this, year, month, day)
}

interface DatePickerFragmentListener {
    fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int)
}

override fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
    datePickerListener?.onDateSet(view,year, month, day)
}
}

我想在 TextInputField 具有焦点时显示日期选择器。这是我导航到 DatePicker

的代码
private fun showDatePicker(hasFocus: Boolean, view: View) {
    Log.i(FRAGMENT_NAME, "Has focus $hasFocus")
    if (hasFocus) {
        Navigation.findNavController(view).navigate(R.id.action_createPatientDetailsFragment_to_datePickerFragment)
    }
}

这是我的导航图的相关部分xml

<fragment android:id="@+id/createPatientDetailsFragment"
          android:name="com.datacollection.ui.patients.create_patient.patient_details.CreatePatientDetailsFragment"
          android:label="create_patient_details_fragment"
          tools:layout="@layout/create_patient_details_fragment">
    <action android:id="@+id/action_createPatientDetailsFragment_to_datePickerFragment"
            app:destination="@id/datePickerFragment"/>
</fragment>
<dialog
        android:id="@+id/datePickerFragment"
        android:name="com.datacollection.ui.DatePickerFragment"/>

我使用的导航控制器版本:2.1.0-alpha04

这是我的问题:

  1. 如何显示对话框片段?
  2. 如何找到我的 DatePicker 片段的 id,我猜是 R.id.datePickerFragment

如果您需要更多信息或需要查看我的更多代码,请告诉我。

这样使用:

<dialog-fragment
    android:id="@+id/my_dialog"
    android:name="com.example.ui.MyDialogFragment"
    tools:layout="@layout/my_dialog" />

而不是:

<dialog
    android:id="@+id/datePickerFragment"
    android:name="com.datacollection.ui.DatePickerFragment"/>

待发布:

findNavController().navigate(R.id.my_dialog)

Navigation Architecture Component中你不能直接使用dialog

1.如何显示对话框片段?

异常说 是你的 activity 运行? DialogFragment 需要 activity/fragment 的上下文而不是应用程序。更新 DatePickerFragment

的下方行
return DatePickerDialog(VitrixDataCollectionApp.context, this, year, month, day)

return DatePickerDialog(context, this, year, month, day)

in kotlin context 是您要扩展的 framgent 的 属性。对于 java 你可以使用 getContext().