【发布时间】:2022-07-19 23:52:07
【问题描述】:
所以基本上我想使用 datePickerDialog 从用户那里获取年份,然后将该年份减去当前年份。直到这我没有问题。 问题是我创建了按钮并希望用户在没有选择日期的情况下收到 Toast 消息。我正在使用 if else 并在未选择 datePicker 时验证年份。 我在 datePickerDialog 之后得到的年份也是当前年份。
这是代码 -
fun birthdayPicker() {
val cal = Calendar.getInstance()
val year = cal.get(Calendar.YEAR)
val month = cal.get(Calendar.MONTH)
val date = cal.get(Calendar.DATE)
val textcheck : TextView = findViewById(R.id.yourage)
val dateSelected = findViewById<TextView>(R.id.text_view_date_1)
dateSelected.setOnClickListener {
val datePickerDialog = DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener { _, myear, mmonth, mdayOfMonth ->
dateSelected.setText("" + mdayOfMonth + "/" + mmonth + "/" + myear)
// Toast.makeText(this, "$myear", Toast.LENGTH_SHORT).show()
},
year,
month + 1,
date
)
datePickerDialog.show()
}
val button = findViewById<Button>(R.id.button_date_1)
button.setOnClickListener {
val selectedyear : Int = year
if (selectedyear.toString().isBlank()) {
Log.e("Main","$selectedyear")
Toast.makeText(this, "Choose an Year", Toast.LENGTH_SHORT).show()
}
else {
val checkingYear = Calendar.getInstance().get(Calendar.YEAR)
textcheck.text = (checkingYear - selectedyear).toString()
}
}
}
【问题讨论】:
标签: android android-studio kotlin