安卓开发日记12
DatePickerHelper
import android.app.DatePickerDialog
import android.content.Context
import android.widget.DatePicker
import android.widget.EditText
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
class DatePickerHelper(private val context: Context) {
fun attachDatePicker(editText: EditText) {
editText.setOnClickListener {
showDatePickerDialog(editText)
}
}
fun showDatePickerDialog(editText: EditText) {
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH)
val datePickerDialog = DatePickerDialog(
context,
{ _: DatePicker, selectedYear: Int, selectedMonth: Int, selectedDayOfMonth: Int ->
val selectedDate = "$selectedDayOfMonth/${selectedMonth + 1}/$selectedYear"
editText.setText(selectedDate)
},
year,
month,
dayOfMonth
)
datePickerDialog.show()
}
fun formatDate(dateString: String): String {
val dateFormat = SimpleDateFormat("yyyy/M/d", Locale.getDefault())
val date = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).parse(dateString)
return dateFormat.format(date)
}
}
实现
val etTime = findViewById<EditText>(R.id.user_et_time)
val datePickerHelper = DatePickerHelper(this)
// 将日期选择器附加到 user_et_time EditText 上
// 设置 EditText 的点击事件监听器
etTime.setOnClickListener {
datePickerHelper.showDatePickerDialog(etTime)
}
//对应格式
val date = datePickerHelper.formatDate(selectedDate)
<EditText
android:id="@+id/user_et_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/user_tv_grade"
android:layout_below="@id/user_et_grade"
android:hint="请输入日期"
android:minLines="2"/>