此解决方案也适用于侦听器以及以编程方式设置时间时。
import android.content.Context
import android.util.AttributeSet
import android.widget.NumberPicker
import android.widget.TimePicker
import androidx.databinding.BindingAdapter
import java.lang.reflect.Field
import java.util.*
class TimePickerInterval @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : TimePicker(context, attrs, defStyleAttr) {
private var MINUTE_INTERVAL = 1
override fun getCurrentMinute(): Int {
return super.getCurrentMinute() * MINUTE_INTERVAL
}
override fun getMinute(): Int {
return super.getMinute() * MINUTE_INTERVAL
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
setUp()
}
private fun setUp() {
try {
val classForid = Class.forName("com.android.internal.R\$id")
val field: Field = classForid.getField("minute")
val mMinuteSpinner = findViewById<NumberPicker>(field.getInt(null))
mMinuteSpinner.minValue = 0
mMinuteSpinner.maxValue = 60 / MINUTE_INTERVAL - 1
val displayedValues: MutableList<String> = ArrayList()
var i = 0
while (i < 60) {
displayedValues.add(String.format("%02d", i))
i += MINUTE_INTERVAL
}
mMinuteSpinner.displayedValues = displayedValues.toTypedArray()
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun setOnTimeChangedListener(onTimeChangedListener: OnTimeChangedListener) {
super.setOnTimeChangedListener { tp, hour, minute ->
onTimeChangedListener.onTimeChanged(tp, hour, minute * MINUTE_INTERVAL)
}
}
override fun setMinute(minute: Int) {
super.setMinute(minute/MINUTE_INTERVAL)
}
companion object {
@JvmStatic
@BindingAdapter("time_picker_set_minute_interval")
fun setInterval(view: TimePickerInterval, interval: Int?) {
interval?.let {
view.MINUTE_INTERVAL = interval
view.setUp()
}
}
}
}
在您的 XML 中:
<com.gixon.shared.widgets.TimePickerInterval
android:id="@+id/tp_to"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:timePickerMode="spinner"
time_picker_set_minute_interval="@{5}"
/>