New to android development and can’t seem to figure out how to get a TimePicker to pop up when an item/View in my RecyclerView item is clicked. I have a Fragment with a RecyclerView and I’ve followed https://developer.android.com/guide/topics/ui/controls/pickers, but, when I click the item, the screen simply dims a bit and that’s it. The Picker never gets displayed.
Thank you.
MainActivity.kt
class MainActivity : AppCompatActivity() {
//...
override fun onCreate(savedInstanceState: Bundle?) {
//...
navigation.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
//...
}
private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_people -> {
findViewById<TextView>(R.id.title).text = "People"
supportFragmentManager.transaction(allowStateLoss = true) {
replace(R.id.container, PeopleFragment.newInstance())
}
return@OnNavigationItemSelectedListener true
}
//...
}
false
}
}
Adapter.kt
class Adapter: ListAdapter<Person, PeopleViewAdapter.ViewHolder>(PeopleDiffCallback()) {
//...
class ViewHolder(val binding: FragmentPeopleDetailBinding) : RecyclerView.ViewHolder(binding.root),
View.OnClickListener, CompoundButton.OnCheckedChangeListener, ChipGroup.OnCheckedChangeListener {
//...
override fun onClick(v: View?) {
v?.let {
when (v.id) {
//...
itemView.start.id -> TimePickerFragment.newInstance(1, 1)
.show((v.context as AppCompatActivity).supportFragmentManager, "Test")
//...
}
}
}
}
//..
}
TimePickerFragment.kt
class TimePickerFragment : DialogFragment(), TimePickerDialog.OnTimeSetListener {
companion object {
fun newInstance(hour: Int, minute: Int) = DialogFragment().apply {
arguments = Bundle().apply {
putInt("hour", hour)
putInt("minute", minute)
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
super.onCreateDialog(savedInstanceState)
var hour = 1
var minute = 1
arguments?.let {
hour = it.getInt("hour")
minute = it.getInt("minute")
}
return TimePickerDialog(activity, this, hour, minute, DateFormat.is24HourFormat(context))
}
override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
Log.d(TAG, "Picked $hourOfDay for hour and $minute for minute.")
}
}
Answering a rather old question of mine, I resolved this by using the new MaterialTimePicker instead. TimePickerFragment.kt is gone and I’ve updated the adapter with what’s below. While I don’t believe the adapter is the best place for this, this is where it currently resides.
MaterialTimePicker.newInstance().apply {
setTimeFormat(TimeFormat.CLOCK_24H)
show((context as AppCompatActivity).supportFragmentManager, null)
setListener { dialog ->
...
}
}