【发布时间】:2019-07-15 19:36:12
【问题描述】:
我是 Kotlin 和 Android 应用程序开发的新手。
我正在学习在线课程,其中一个练习是选择日期以在特定时间提醒要完成的项目。
我所做的是创建了 EditText 并实现了 DatePicker。当用户点击打开日期选择器并选择日期后,我无法设置为 EditText 的文本。
顺便说一句,我已经检查了其他相关问题,它说检查您的 id 以确保您在正确的布局文件中引用非空小部件。我仔细检查了它,这不是问题
这是错误。
尝试在空对象引用上调用虚拟方法“void android.widget.EditText.setText(java.lang.CharSequence)”
//EditText on layout file
<EditText
android:id="@+id/calendarEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Select your date"
android:focusable="false"
/>
//My Kotlin code
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
//DatePicker is called inside onCreate function
calendarEditText.setOnClickListener {
val newFragment = DatePickerFragment()
newFragment.show(supportFragmentManager, "datePicker")
}
}
// DateSet part of my DatePickerFragment
override fun onDateSet(view: DatePicker, year: Int, month: Int, dayOfMonth: Int) {
//selected date converted into one string
val date = "$year/$month/$dayOfMonth"
//this is where I got the error
calendarEditText.setText(date)
}
【问题讨论】:
-
尝试使用
findViewById()。 -
感谢您的建议,但在 Kotlin 中您不需要 findViewById() 并且已经通过直接调用 ID 在前面的行中进行了测试
标签: android kotlin datepicker android-edittext android-datepicker