【问题标题】:How to set Text for EditText with Date Picker in Kotlin如何在 Kotlin 中使用日期选择器为 EditText 设置文本
【发布时间】: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


【解决方案1】:

对我来说,calendarEditText 为空,因为您在 DatePickerFragment 中调用它,因此您处于不同的上下文中。

在你的 onDataSet 中,像这样更新edittext:

((MyActivity) activity).setEdt(date);

在你的活动中,类似的东西:

public setEdt(date: String): void {
calendarEditText.setText(date)
}

或关注此tuto 以避免碎片

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多