---
# System prepended metadata

title: CustomCalendarView
tags: [View, Android, Kotlin]

---

###### tags: `Android` `Kotlin` `View`
# CustomCalendarView
在Android中要使用月曆，可以用原生的CalendarView，但僅提供時間的選擇，想要其他功能
就要擴充或自製，在這裡我引用別人刻好的CalendarView 並增加了一些常見的功能
以下是此元件的使用方式：

```kotlin=
calendarPicker.showDateTitle(true) //要不要顯示Month
calendarPicker.setDisableWeek(arrayOf(1, 2)) //不可選擇的星期 1~7(日~六)
calendarPicker.setShortWeekDays(true) //星期字數簡短
calendarPicker.minDate = Date() //設定最小日期，此時間之前的日子會被disable
calendarPicker.date = Date()  //設定目前日期，此時間會被灰色圈框住

//取得被選中日期
btn_selected.setOnClickListener{ v -> Log.e("time", calendarPicker.selectedDate.toString()) }

//清除被選的日期
btn_clean.setOnClickListener { v -> calendarPicker.clearSelectedDay() }

//設定日期下方的小圈
btn_mark.setOnClickListener { view ->
    val calendar = Calendar.getInstance()
    val random = Random(System.currentTimeMillis())
    val style = random.nextInt(2)
    val daySelected = random.nextInt(calendar.getActualMaximum(Calendar.DAY_OF_MONTH))
    calendar.set(Calendar.DAY_OF_MONTH, daySelected)

    when (style) {
        0 -> calendarPicker.markCircleImage1(calendar.time)
        1 -> calendarPicker.markCircleImage2(calendar.time)
        else -> {}
    }
}

//設定監聽
calendarPicker.setCustomCalendarListener(object : CustomCalendarView.CustomCalendarListener {
    override fun onDayClick(date: Date) {
        Toast.makeText(this@MainActivity, "onDayClick: $date", Toast.LENGTH_SHORT).show()
    }

    override fun onDayLongClick(date: Date) {
        Toast.makeText(this@MainActivity, "onDayLongClick: $date", Toast.LENGTH_SHORT).show()
    }

    override fun onLeftButtonClick() {
        Toast.makeText(this@MainActivity, "onRightButtonClick", Toast.LENGTH_SHORT).show()
    }

    override fun onRightButtonClick() {
        Toast.makeText(this@MainActivity, "onLeftButtonClick", Toast.LENGTH_SHORT).show()
    }
})
```


> GitHub：https://github.com/t104360088/AndroidNote/tree/master/MyCalendarView
> 參考：https://github.com/marcohc/roboto-calendar-view