如何在Kotlin中使用DatePickerDialog?

时间:2017-08-23 14:11:32

标签: kotlin datepickerdialog

在Java中,可以使用DatePickerDialog,例如:

final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);


DatePickerDialog dpd = new DatePickerDialog(getActivity(),new DatePickerDialog.OnDateSetListener()
{
   @Override
   public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
  {
      // Display Selected date in textbox
      lblDate.setText(""+ dayOfMonth+" "+MONTHS[monthOfYear] + ", " + year);
  }
}, year, month,day);
dpd.show();

Kotlin的DatePickerDialog如何使用?

6 个答案:

答案 0 :(得分:37)

它看起来像这样:

android:paddingStart

这是通过简单地将代码复制并粘贴到android studio中的kotlin文件中完成的。我强烈建议使用它。

答案 1 :(得分:6)

Kotlin Anko Android示例:

alert {

    isCancelable = false

    lateinit var datePicker: DatePicker

    customView {
        verticalLayout {
            datePicker = datePicker {
                maxDate = System.currentTimeMillis()
            }
        }
    }

    yesButton {
        val parsedDate = "${datePicker.dayOfMonth}/${datePicker.month + 1}/${datePicker.year}"
    }

    noButton { }

}.show()

答案 2 :(得分:2)

如果您想使用协程来桥接回调模式,则可以使用类似的解决方案。请注意,我在这里同时使用了“日期和时间”选择器,但是如果不需要它,您可以轻松地删除“时间选择器”逻辑。

suspend fun Context.openDateTimePicker(calendar: Calendar = Calendar.getInstance()): Instant =
    suspendCoroutine { continuation ->
        val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, month, day ->
            val timeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
                calendar
                    .apply { set(year, month, day, hour, minute) }
                    .run { Instant.ofEpochMilli(timeInMillis).truncatedTo(ChronoUnit.MINUTES) }
                    .let { continuation.resume(it) }
            }

            TimePickerDialog(
                this,
                timeSetListener,
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                DateFormat.is24HourFormat(this)
            ).show()
        }

        DatePickerDialog(
            this,
            dateSetListener,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

答案 3 :(得分:1)

我使用Kotlin,所以我想要Kotlin解决方案,而不是Java解决方案。

因此,首先,我仔细考虑@FrostRocket的解决方案。 @FrostRocket的解决方案对我有用。

就我而言,我无视整个Kotlin世界。以及我只能使用OffsetDateTime而不是日历类。此外,我以前从未使用过协程,因此我必须在Kotlin内阅读和研究协程。如果您在我的代码中发现一些理论或实践错误,请告诉我。

首先在扩展程序包中添加一个新文件:ContextExtention.kt

import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import android.text.format.DateFormat
import java.time.OffsetDateTime
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

    suspend fun Context.openDateTimePicker(offsetDateTime: OffsetDateTime = OffsetDateTime.now()): OffsetDateTime =
suspendCoroutine { continuation ->
    val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, month, day ->
        //month (0-11 for compatibility with Calendar#MONTH)
        // day of the month (1-31, depending on month)
        val timeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
            offsetDateTime.let {
            val newOffsetDateTime =
                offsetDateTime.withHour(hour).withMinute(minute).withYear(year)
                    //withMonth from 1 (January) to 12 (December)
                    //so I have to adapt it.
                    .withMonth((month+1))
                    //withDayOfMonth from 1 to 28-31
                    //so no need adaptation
                    .withDayOfMonth(day)
                    continuation.resume(newOffsetDateTime)
                }
        }

        TimePickerDialog(
            this,
            timeSetListener,
            offsetDateTime.hour,
            offsetDateTime.minute,
            DateFormat.is24HourFormat(this)
        ).show()
    }

    //the initially selected month (0-11 for compatibility with Calendar#MONTH)
    //when offsetDateTime.monthValue from 1 (January) to 12 (December)
    //so I have to adapt it.
    DatePickerDialog(
        this,
        dateSetListener,
        offsetDateTime.year,
        (offsetDateTime.monthValue-1),
        offsetDateTime.dayOfMonth
    ).show()
}

那么我该如何运行一个暂停的功能?因此,您在kotlinx.coroutines.Job中运行了一个协程,CoroutineScope使我回想起iPhone编程中的Grand Central Dispatcher,那里有一系列服务质量。

在这种情况下,如果要使用UI线程,则必须使用:Dispatchers.Main或Dispatchers.Main.immediate(如果需要更好的服务)。

import android.widget.TextView
import androidx.lifecycle.Observer
// the R import here 
// the openDateTimePicker import here 
// the TimeHelper (is text formatter) import here 
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch


class FooFragment : Fragment() {

private lateinit var viewModel: FooViewModel

private lateinit var dateButton: Button
private lateinit var dateText: TextView
private var datePickerJob : Job? = null
val uiScope = CoroutineScope(Dispatchers.Main)

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val root =
     inflater.inflate(R.layout.foo_fragment, container, false)
    dateButton = root.findViewById(R.id.textButtonChangeDate)
    dateText = root.findViewById(R.id.textViewWeighingDateValue)
    viewModel = ViewModelProvider(this).get(FooViewModel::class.java)
    return root
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    viewModel.dateTimeText.observe(viewLifecycleOwner, Observer {
        dateText.text = it.format(TimeHelper.formatter)
//the call to setNewDateTime will refresh this value
    })
}

override fun onStart() {
    super.onStart()
    dateButton.setOnClickListener {
        datePickerJob = uiScope.launch {
            viewModel.setNewDateTime(context?.openDateTimePicker())
//setNewDateTime is a setValue in a MutableLiveData
        }
    }

}

override fun onStop() {
    super.onStop()
    dateButton.setOnClickListener(null)
    datePickerJob?.cancel()
}

}

答案 4 :(得分:0)

在按钮上使用显示日期选择器

   val cal = Calendar.getInstance()
    val y = cal.get(Calendar.YEAR)
    val m = cal.get(Calendar.MONTH)
    val d = cal.get(Calendar.DAY_OF_MONTH)


    val datepickerdialog:DatePickerDialog = DatePickerDialog(activity, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->

    // Display Selected date in textbox
    lblDate.setText("" + dayOfMonth + " " + MONTHS[monthOfYear] + ", " + year)
        }, y, m, d)

    datepickerdialog.show()

这用于在单击按钮时显示时间选择器

textView54.setOnClickListener {
                val c:Calendar= Calendar.getInstance()
                val hh=c.get(Calendar.HOUR_OF_DAY)
                val mm=c.get(Calendar.MINUTE)
                val timePickerDialog:TimePickerDialog=TimePickerDialog(this@VendorRegistration,TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute ->
                    textView54.setText( ""+hourOfDay + ":" + minute);
                },hh,mm,true)
                timePickerDialog.show()

答案 5 :(得分:0)

dateColumn.setOnClickListener {
        val c = Calendar.getInstance()
        val yr = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH)
        val day = c.get(Calendar.DAY_OF_MONTH)
        val display = DatePickerDialog(context as BaseActivity, DatePickerDialog.OnDateSetListener {
                view, year, monthOfYear, dayOfMonth ->
            var monthInput = (monthOfYear + 1).toString()
            if (monthInput.toInt() == 1) {
                monthInput = "Jan"
            } else if (monthInput.toInt() == 2) {
                monthInput = "Feb"
            } else if (monthInput.toInt() == 3) {
                monthInput = "March"
            } else if (monthInput.toInt() == 4) {
                monthInput = "April"
            } else if (monthInput.toInt() == 5) {
                monthInput = "May"
            } else if (monthInput.toInt() == 6) {
                monthInput = "June"
            } else if (monthInput.toInt() == 7) {
                monthInput = "July"
            } else if (monthInput.toInt() == 8) {
                monthInput = "Aug"
            } else if (monthInput.toInt() == 9) {
                monthInput = "Sept"
            } else if (monthInput.toInt() == 10) {
                monthInput = "Oct"
            } else if (monthInput.toInt() == 11) {
                monthInput = "Nov"
            } else if (monthInput.toInt() == 12) {
                monthInput = "Dec"
            }
            dateColumn.text = ("$dayOfMonth $monthInput, $year")
        }, yr, month, day)
        display.datePicker.minDate = System.currentTimeMillis()
        display.show()
    }