Kotlin(不能将null强制转换为非null类型)自定义日历实现

问题描述 投票:0回答:1

我正在尝试使用Java中的库https://github.com/kizitonwose/CalendarView(由Kotlin制造)。在该库中,有一个选择日期的示例。在示例中,它显示了这样做:

    private fun selectDate(date: LocalDate) {
    if (selectedDate != date) {
        val oldDate = selectedDate
        selectedDate = date
        oldDate?.let { exThreeCalendar.notifyDateChanged(it) }
        exThreeCalendar.notifyDateChanged(date)
        updateAdapterForDate(date)
    }
}

尝试在我自己的android项目中复制此代码后,我这样写:

    private void selectDate(LocalDate date){
        if(selectedDate != date){
            // oldDate is null
            // date is not null
            LocalDate oldDate = selectedDate;
            selectedDate = date;
            if (oldDate != null){
                calendarView.notifyDateChanged(oldDate);
            }
            calendarView.notifyDateChanged(date);
            updateAdapterForDate(date);
            }
        }

当我的片段启动时,它以今天的日期作为参数(不为null)调用selectDate()方法。它在

上给出错误
calendarView.notifyDateChanged(date);

saying

 null cannot be cast to non-null type com.kizitonwose.calendarview.ui.CalendarAdapter

我想知道如何实现相同的结果

oldDate?.let { exThreeCalendar.notifyDateChanged(it) }

在Java中,或者我的代码中还有其他不正确的地方。感谢您的帮助。

java android kotlin view calendar
1个回答
0
投票

注意错误消息中的类型。不是date为空,而是CalendarAdapter类型,我怀疑

private val calendarAdapter: CalendarAdapter
    get() = adapter as CalendarAdapter

看起来adapter应该在setup中设置,也许您没有调用它?

© www.soinside.com 2019 - 2024. All rights reserved.