【问题标题】:How to Store an YEAR from DatePickerDialog in Kotlin?如何在 Kotlin 中存储 DatePickerDialog 的年份?
【发布时间】: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


    【解决方案1】:

    所以你只需将它存储到一个变量中

            val myFormat = "MM/dd/yyyy" //mention the format you need
            val sdf = SimpleDateFormat(myFormat, Locale.US)
            val currentDate = sdf.format(cal.getTime())
    

    【讨论】:

      猜你喜欢
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      相关资源
      最近更新 更多