我正在尝试从DatePicker获取值,但是我不知道如何管理它。
我的布局包含一个DatePicker元素,并且我正在使用kotlin。
TimePicker出现相同的问题。
答案 0 :(得分:0)
您能具体一点吗?是否要向用户显示DatePicker和TimePicker并获取用户选择的值?在这种情况下,您可以尝试这样。 对于DatePicker,
val mCalendar = Calendar.getInstance()
val mYear = mCalendar.get(Calendar.YEAR)
val mMonth = mCalendar.get(Calendar.MONTH)
val mDay = mCalendar.get(Calendar.DAY_OF_MONTH)
val dpd = DatePickerDialog(
this, DatePickerDialog.OnDateSetListener { _, thisYear, thisMonth, thisDay ->
mYear = thisYear
mMonth = thisMonth
mDay = thisDay
tDate.text = mDay.toString() + "/" + (mMonth + 1).toString() +
"/" + mYear.toString()
}, mYear, mMonth, mDay
)
dpd.show()
对于TimePicker,
TimePickerDialog(this, TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
tvHour.text = Calendar.HOUR_OF_DAY, hourOfDay
tvMinute.text = Calendar.MINUTE, minute
}, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE), false).show()
答案 1 :(得分:0)
此帮助器类同时实现了DatePicker和TimePicker的魔力:
data class DatePickerChangeEvent(
val view: View,
val year: Int = 0,
val monthOfYear: Int = 0,
val dayOfMonth: Int = 0
)
data class TimePickerChangeEvent(
val view: View,
val hour: Int,
val minute: Int
)
class DatePickerObservable(val view: DatePicker, val year: Int, val monthOfYear: Int, val dayOfMonth: Int)
: io.reactivex.Observable<DatePickerChangeEvent>() {
override fun subscribeActual(observer: Observer<in DatePickerChangeEvent>) {
val listener = DateChangeListener(view, observer)
observer.onSubscribe(listener)
view.init(year, monthOfYear, dayOfMonth, listener)
}
class DateChangeListener(private val dp: DatePicker, private val obs: io.reactivex.Observer<in DatePickerChangeEvent>)
: DatePicker.OnDateChangedListener, MainThreadDisposable() {
override fun onDateChanged(p0: DatePicker, p1: Int, p2: Int, p3: Int) {
obs.onNext(DatePickerChangeEvent(dp, p1, p2, p3))
}
override fun onDispose() {
}
}
}
class TimePickerObservable(val view: TimePicker)
: io.reactivex.Observable<TimePickerChangeEvent>() {
override fun subscribeActual(observer: Observer<in TimePickerChangeEvent>) {
val listener = TimeChangeListener(view, observer)
observer.onSubscribe(listener)
view.setOnTimeChangedListener(listener)
}
class TimeChangeListener(private val tp: TimePicker, private val obs: io.reactivex.Observer<in TimePickerChangeEvent>)
: TimePicker.OnTimeChangedListener, MainThreadDisposable() {
override fun onTimeChanged(p0: TimePicker, p1: Int, p2: Int) {
obs.onNext(TimePickerChangeEvent(p0, p1, p2))
}
override fun onDispose() {
tp.setOnTimeChangedListener { timePicker, i, i2 -> }
}
}
}
@Suppress("NOTHING_TO_INLINE")
inline fun DatePicker.dateChange(year: Int, monthOfYear: Int, dayOfMonth: Int): DatePickerObservable =
DatePickerObservable(this, year, monthOfYear, dayOfMonth)
@Suppress("NOTHING_TO_INLINE")
inline fun TimePicker.timeChange(): TimePickerObservable =
TimePickerObservable(this)
比你可以称呼它:
datePicker.dateChange(2018,9,15)
.subscribe{
Log.d("RxDate", it.toString())
}