Reputation: 34
I have created a code to show a time picker dialog, I used this Android API Code, But As in it, the code doesn't work Because I couldn't call the supportFragmentManager.Here is my Code as follow,
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")
}
}
Upvotes: 1
Views: 1483
Reputation: 19562
You're in a Fragment
, not an Activity
You can get the
FragmentManager
by callinggetSupportFragmentManager()
from theFragmentActivity
orgetFragmentManager()
from aFragment
.
so you need getFragmentManager()
(or just fragmentManager
in Kotlin) - or parentFragmentManager
if you want, the former's deprecated and tells you to use this instead
Upvotes: 2
Reputation: 866
Please try,
val transaction = supportFragmentManager.beginTransaction()
timePicker.show(transaction,"time_picker")
Upvotes: 2