如何降低Android中DatePickerDialog代码的复杂性?

时间:2019-06-13 10:30:27

标签: android kotlin datepickerdialog

我正在尝试实现日期选择器。 如果用户从未选择任何日期,它将显示当前日期, 否则,它将显示用户先前选择的日期。

但是对于这样一个简单的任务,我认为我的代码不必要地复杂并且编写得不太好:

findViewById<LinearLayout>(R.id.settings_starting_date)
    .setOnClickListener {

        val dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM)
        val dateToday = Calendar.getInstance()
        val dateString = dateFormat.format(dateToday.time)

        val prefs = getSharedPreferences(getString(R.string.shared_prefs_settings), Context.MODE_PRIVATE)
        val theDateString = prefs.getString("starting_date", dateString)
        val theTime = dateFormat.parse(theDateString)
        val theDate = Calendar.getInstance()
        theDate.time = theTime
        val theDay = theDate.get(Calendar.DAY_OF_MONTH)
        val theMonth = theDate.get(Calendar.MONTH)
        val theYear = theDate.get(Calendar.YEAR)

        val theDialog = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
            val dateSelected = Calendar.getInstance()
            dateSelected.set(Calendar.DAY_OF_MONTH, dayOfMonth)
            dateSelected.set(Calendar.MONTH, month)
            dateSelected.set(Calendar.YEAR, year)

            val dateSelectedString = dateFormat.format(dateSelected.time)

            val editor = prefs.edit()
            editor
                .putString("starting_date", dateSelectedString)
                .apply()

            val startingDate = findViewById<LinearLayout>(R.id.settings_starting_date)
            startingDate.findViewById<TextView>(R.id.secondary_text).text = dateSelectedString

        }, theYear, theMonth, theDay)
        theDialog.show()

    }

我认为日期和字符串之间的转换应该更简单, 但我不知道该怎么办?

0 个答案:

没有答案