728x90
1편에 이어서 2편을 작성해 보겠습니다.
CalendarAdapter를 생성해서 CalendarFragment에서의 리사이클러뷰 어댑터를 연결시켜 줍니다.
class CalendarAdapter(private val context: Context,private val calendarLayout: LinearLayout,private val date: Date) : RecyclerView.Adapter<CalendarAdapter.CalendarItemHolder>() {
var dataList: ArrayList<Int> = arrayListOf()
var dateCalendar= DateCalendar(date)
init {
dateCalendar.initBaseCalendar()
dataList = dateCalendar.dateList
}
override fun onBindViewHolder(holder: CalendarItemHolder, position: Int) {
val h = calendarLayout.height / 6
holder.itemView.layoutParams.height = h
holder.bind(dataList[position], position, context)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CalendarItemHolder {
val binding = ItemCalendarDateListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return CalendarItemHolder(binding)
}
override fun getItemCount(): Int = dataList.size
inner class CalendarItemHolder(private val binding : ItemCalendarDateListBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(data: Int, position: Int, context: Context) {
val firstDateIndex = dateCalendar.prevTail
val lastDateIndex = dataList.size - dateCalendar.nextHead - 1
binding.itemCalendarDateText.text = data.toString()
if (position < firstDateIndex || position > lastDateIndex) {
binding.itemCalendarDateText.alpha = 0.4f
}else{
binding.itemCalendarDateText.alpha = 1f
}
}
}
}
Class DateCalendar 생성.
class DateCalendar(date: Date) {
private val DAYS_OF_WEEK = 7
private val LOW_OF_CALENDAR = 6
private val calendar = Calendar.getInstance()
var prevTail = 0
var nextHead = 0
var currentMaxDate = 0
var dateList = arrayListOf<Int>()
init {
calendar.time = date
}
fun initBaseCalendar() {
makeMonthDate()
}
private fun makeMonthDate() {
dateList.clear()
calendar.set(Calendar.DATE, 1)
currentMaxDate = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
prevTail = calendar.get(Calendar.DAY_OF_WEEK) - 1
makePrevTail(calendar.clone() as Calendar)
makeCurrentMonth(calendar)
nextHead = LOW_OF_CALENDAR * DAYS_OF_WEEK - (prevTail + currentMaxDate)
makeNextHead()
}
private fun makePrevTail(calendar: Calendar) {
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1)
val maxDate = calendar.getActualMaximum(Calendar.DATE)
var maxOffsetDate = maxDate - prevTail
for (i in 1..prevTail) dateList.add(++maxOffsetDate)
}
private fun makeCurrentMonth(calendar: Calendar) {
for (i in 1..calendar.getActualMaximum(Calendar.DATE)) dateList.add(i)
}
private fun makeNextHead() {
var date = 1
for (i in 1..nextHead) dateList.add(date++)
}
}
부족한 설명은 시간났을때 자세히 설명하겠습니다. 감사합니다~
'안드로이드' 카테고리의 다른 글
현재좌표 로케이션 (0) | 2022.10.15 |
---|---|
[Android] Android Studio 이미지 흔들리는 애니메이션 효과 적용! (2) | 2022.10.14 |
[ Android/ Kotlin ] xml RSS Feed 파싱하기 1편 (0) | 2022.04.27 |
[Android/ Kotlin] ExoPlayer2 PlayControlView Custom하기! (0) | 2022.04.26 |
[Android / Kotlin ] ViewPager2 로 달력만들기 1편 (0) | 2022.04.26 |