[英]How to set Text for EditText with Date Picker in Kotlin
I am new to Kotlin and android app development. 我是Kotlin和android应用程序开发的新手。
I am following a online course and one of the exercises is picking date to remind a to do item at certain time. 我正在关注在线课程,其中一项练习是在特定时间选择日期来提醒待办事项。
What i did is created EditText and implemented DatePicker. 我所做的是创建EditText并实现了DatePicker。 When user clicks date picker is opened and after I select the date, I can not set to text of EditText. 当用户单击日期选择器打开时,当我选择日期后,无法将文本设置为EditText。
BTW I already checked other related questions and it says check your id to make sure you are referring to non null widget in correct layout file. 顺便说一句,我已经检查了其他相关问题,它说检查您的ID,以确保您引用的是正确的布局文件中的非null小部件。 I double checked it and it is not the problem 我仔细检查了一下,这不是问题
Here is the error. 这是错误。
Attempt to invoke virtual method 'void android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference 尝试在空对象引用上调用虚拟方法'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)
}
for me calendarEditText is null because you call it in a DatePickerFragment, so you are in a different context. 对我而言,calendarEditText为null,因为您在DatePickerFragment中调用它,所以您处于不同的上下文中。
In your onDataSet, update edittext like that : 在您的onDataSet中,像这样更新edittext:
((MyActivity) activity).setEdt(date);
and in your activity, something like that : 在您的活动中,类似这样的内容:
public setEdt(date: String): void {
calendarEditText.setText(date)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.