Kotlin
获取选定日期的示例代码CalenderView
:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<CalendarView
android:id="@+id/calendar_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Toast Selected Date" />
</LinearLayout>
MainActivity.kt
import android.os.Bundle
import android.text.format.DateFormat
import android.util.Log
import android.widget.CalendarView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.testandcheck.databinding.ActivityMainBinding
import java.util.*
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding // Binding object for ViewBinding.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Set date change listener on calenderView.
// Callback notified when user select a date from CalenderView on UI.
binding.calendarView.setOnDateChangeListener { calView: CalendarView, year: Int, month: Int, dayOfMonth: Int ->
// Create calender object with which will have system date time.
val calender: Calendar = Calendar.getInstance()
// Set attributes in calender object as per selected date.
calender.set(year, month, dayOfMonth)
// Now set calenderView with this calender object to highlight selected date on UI.
calView.setDate(calender.timeInMillis, true, true)
Log.d("SelectedDate", "$dayOfMonth/${month + 1}/$year")
}
// Example button to show get selected date from CalenderView and show in Toast.
binding.button.setOnClickListener {
// Fetch long milliseconds from calenderView.
val dateMillis: Long = binding.calendarView.date
// Create Date object from milliseconds.
val date: Date = Date(dateMillis)
// Get Date values and created formatted string date to show in Toast.
val selectedDayOfWeek = DateFormat.format("EEEE", date) as String // Monday
val selectedDay = DateFormat.format("dd", date) as String // 05
val selectedMonthString = DateFormat.format("MMM", date) as String // Jul
val selectedMonthNumber = DateFormat.format("MM", date) as String // 6 --> Month Code as Jan = 0 till Dec = 11.
val selectedYear = DateFormat.format("yyyy", date) as String // 2021
val strFormattedSelectedDate = "$selectedDay-${selectedMonthNumber + 1}-$selectedYear ($selectedDayOfWeek)"
Toast.makeText(applicationContext, "Selected Date = $strFormattedSelectedDate", Toast.LENGTH_SHORT).show()
}
}
}
说明:
- 设置侦听器以设置所选日期
CalenderView
(同时突出显示新选择的日期并取消突出显示较旧的日期)。
- 然后只调用
calenderView.date
以获取选定的日期。