使用 Kotlin 显示对话片段

Show a Dialog Fragment using Kotlin

我已经创建了一个代码来显示时间选择器对话框,我使用了这个 Android API Code,但是在其中,代码不起作用因为我无法调用 supportFragmentManager .这是我的代码如下,

AddToDoFragment.kt

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import com.dsgimhana.todoapp.databinding.FragmentAddToDoBinding

class AddToDoFragment : Fragment() {
    private var _binding: FragmentAddToDoBinding? = null

    private val binding get() = _binding!!

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentAddToDoBinding.inflate(inflater,container,false)
        binding.saveToDoBtn.setOnClickListener{view->
            view.findNavController().navigate(R.id.action_addToDoFragment_to_toDoListFragment)
        }
        binding.timePicker.setOnClickListener{view->
            val timePicker = TimePickerFragment()
            timePicker.show(supportFragmentManager,"time_picker")
        }
        return binding.root


    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

TimePickerFragment.kt

import android.app.Dialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.text.format.DateFormat
import android.widget.TimePicker
import androidx.fragment.app.DialogFragment
import java.util.*

class TimePickerFragment : DialogFragment(), TimePickerDialog.OnTimeSetListener {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        // Use the current time as the default values for the picker
        val c = Calendar.getInstance()
        val hour = c.get(Calendar.HOUR_OF_DAY)
        val minute = c.get(Calendar.MINUTE)

        // Create a new instance of TimePickerDialog and return it
        return TimePickerDialog(activity, this, hour, minute, DateFormat.is24HourFormat(activity))
    }

    override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
        TODO("Not yet implemented")
    }
}

请尝试,

val transaction = supportFragmentManager.beginTransaction()
timePicker.show(transaction,"time_picker")

你在 Fragment,而不是 Activity

You can get the FragmentManager by calling getSupportFragmentManager() from the FragmentActivity or getFragmentManager() from a Fragment.

所以你需要 getFragmentManager()(或者在 Kotlin 中只需要 fragmentManager)- 或者 parentFragmentManager 如果你愿意,前者已被弃用并告诉你改用它