관리 메뉴

막내의 막무가내 프로그래밍 & 일상

[안드로이드] 데이터바인딩 어댑터 (DatabindingAdapter) 및 확장함수 모음 정리 본문

안드로이드/코틀린 & 아키텍처 & Recent

[안드로이드] 데이터바인딩 어댑터 (DatabindingAdapter) 및 확장함수 모음 정리

막무가내막내 2021. 1. 7. 20:22
728x90

 

[2021-04-14]

 

이전 프로젝트에서 본인이 사용했던 바인딩 어댑터나 확장함수를 막무가내로 일단 기록해놓는 공간입니다. 

 

[2021-01-07]

일단 사용했던 것들 중 몇개만 기록해 놓습니다.

 

 

 

 

 

[확장함수]

시간변환 관련 확장함수(현재 이전에 개발한 충남대 공지앱을 커뮤니티로 확장 중인 프로젝트에 사용중이다. 캘린더 위주로 시간변환할 예정)

->( convertBoardTime() 같은건 나중에도 개인프로젝트에서 사용할만하다. 1시간 미만은 몇분전 표시 오늘껀 시간:분 그 외에는 날짜와 시간:분을 보여준다.)

package com.mtjin.cnunoticeapp.utils.extensions

import android.text.format.DateFormat
import java.util.*
import java.util.concurrent.TimeUnit

//현재 타임스템프 얻기
fun getTimestamp() = Calendar.getInstance(Locale.KOREA).timeInMillis

fun Long.convertBoardTime(): String {
    val now = Calendar.getInstance(Locale.KOREA)
    val diffInMillis = now.timeInMillis - this //현재와의 밀리초 차이
    //오늘 기준 00시
    now.set(Calendar.HOUR_OF_DAY, 0)
    now.set(Calendar.MINUTE, 0)
    now.set(Calendar.SECOND, 0)
    now.set(Calendar.MILLISECOND, 0)
    //toDays()로 하면 날이 아예 24시간이 자나야 날 수로쳐서 계산이 이상하게됨
    val todayOfHour =
        TimeUnit.MILLISECONDS.toHours(now.timeInMillis)
    val thisOfHour = TimeUnit.MILLISECONDS.toHours(this)
    val currentDiffHour = diffInMillis / 1000 / 60 / 60L //현재와 시간 차이
    return if (currentDiffHour < 1) { //현재시간 60분 전
        (diffInMillis / 1000 / 60L).toString() + "분 전"
    } else {
        if (todayOfHour < thisOfHour || (
                    thisOfHour - todayOfHour in 0..23)
        ) { //오늘
            this.convertHourMinute() //(08:23)
        } else { // 하루 이상 지난 날
            this.convertDateTimeMinute() // (2021.01.07 08:23)
        }
    }
}

//타임스탬프 -> 시간:분 (08:23)
fun Long.convertHourMinute(): String = DateFormat.format("HH:mm", this).toString()

//타임스탬프 -> 날짜 시간:분 (2021.01.07 08:23)
fun Long.convertDateTimeMinute(): String =
    DateFormat.format("yyyy.MM.dd HH:mm", this).toString()

 

 

시간변환 관련 확장 함수 (DateFormat 위주이다.)

@file:Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")

package com.mtjin.nomoneytrip.utils.extensions

import android.text.format.DateFormat
import android.util.Log
import java.text.SimpleDateFormat
import java.util.*
import kotlin.random.Random

// 날짜만 타임스탬프 변환 2020-01-01 - timestamp
fun String.convertDateToTimestamp(): Long =
    SimpleDateFormat("yyyy-MM-dd", Locale.KOREA).parse(this).time

fun Long.convertTimestampToDate(): String = DateFormat.format("yyyy-MM-dd", this).toString()

fun Long.convertTimestampToPointFullDate(): String =
    DateFormat.format("yyyy.MM.dd", this).toString()

fun Long.convertTimestampToPointFullDateTime(): String =
    DateFormat.format("yyyy.MM.dd HH:mm", this).toString()

fun Long.convertTimestampToSlashOnlyDate(): String =
    DateFormat.format("MM/dd", this).toString()


// 날짜,시간,분 포함된 타임스탬프 변환 2020-01-01-22-30 - timestamp
fun String.convertDateFullToTimestamp(): Long =
    SimpleDateFormat("yyyy-MM-dd-HH:mm", Locale.KOREA).parse(this).time

fun Long.convertTimestampToDateFull(): String =
    DateFormat.format("yyyy-MM-dd-HH:mm", this).toString()

fun Long.convertCurrentTimestampToDateTimestamp(): Long =
    this.convertTimestampToDate().convertDateToTimestamp()

// timestamp -> 13:40
fun Long.convertTimestampToTime(): String = DateFormat.format("HH:mm", this).toString()

//fun Long.convertTimesToTimestamp(): Long = DateFormat.format("HH:mm", this).toString()

// 시간 한자리면 앞에 0 붙여주어 변환
fun String.convertHourDoubleDigit(): String = if (this.length < 2) "0$this" else this

// 분 한자리면 앞에 0 붙여주어 반환
fun String.convertMinuteDoubleDigit(): String = if (this.length < 2) "0$this" else this

// 한자리 숫자면 두자리로 변환
fun String.convertSingleToDoubleDigit(): String = if (this.length < 2) "0$this" else this

fun Long.convertTimestampToHour(): Int = DateFormat.format("HH", this).toString().toInt()

fun Long.convertTimestampToMinute(): Int = DateFormat.format("mm", this).toString().toInt()

fun Int.convertNextHour(): Int = if (this == 23) 0 else this + 1

fun Int.convertNextMinute(): Int = if (this == 59) 0 else this + 1

// 다음날의 현재 Year
fun getNextDayCurrentYear(): Int {
    val c = Calendar.getInstance()
    c.add(Calendar.DATE, 1)
    return c.get(Calendar.YEAR)
}

// 다음날의 현재 Month
fun getNextDayCurrentMonth(): Int {
    val c = Calendar.getInstance()
    c.add(Calendar.DATE, 1)
    return if (c.get(Calendar.MONTH) == 11) 12
    else c.get(Calendar.MONTH) + 1
}

// 다음날의 현재 Day
fun getNextDayCurrentDay(): Int {
    val c = Calendar.getInstance()
    c.add(Calendar.DATE, 1)
    return c.get(Calendar.DAY_OF_MONTH)
}


// 현재 Year
fun getCurrentYear(): Int = Calendar.getInstance().get(Calendar.YEAR)

// 현재 Month
fun getCurrentMonth(): Int = Calendar.getInstance().get(Calendar.MONTH) + 1

// 현재 Day
fun getCurrentDay(): Int = Calendar.getInstance().get(Calendar.DAY_OF_MONTH)

// timestamp -> year
fun Long.convertTimestampToYear(): Int {
    val cal: Calendar = Calendar.getInstance()
    cal.timeInMillis = this
    return cal[Calendar.YEAR]
}

// timestamp -> month
fun Long.convertTimestampToMonth(): Int {
    val cal: Calendar = Calendar.getInstance()
    cal.timeInMillis = this
    return cal[Calendar.MONTH] + 1
}

// timestamp -> day
fun Long.convertTimestampToDay(): Int {
    val cal: Calendar = Calendar.getInstance()
    cal.timeInMillis = this
    return cal[Calendar.DAY_OF_MONTH]
}


// 1시간 뒤 타임스탬프
fun Long.convertNextHourTimestamp(): Long = this + (60 * 60 * 1000)

// 2020, 1, 20 -> timestamp
fun convertDateToTimestamp(_year: Int, _month: Int, _day: Int): Long {
    val month = _month.toString().convertSingleToDoubleDigit().toInt()
    val day = _day.toString().convertSingleToDoubleDigit().toInt()
    val date = "$_year-$month-$day"
    return date.convertDateToTimestamp()
}

// timestamp -> 9.6~9.8
fun convertTimestampToTerm(startTimestamp: Long, endTimestamp: Long): String {
    return DateFormat.format("MM-dd", startTimestamp)
        .toString() + "~" + DateFormat.format("MM-dd", endTimestamp).toString()
}

// timestamp -> 9.6~9.8
fun convertTimestampOnlyDateMinusTerm(startTimestamp: Long, endTimestamp: Long): String {
    return DateFormat.format("yyyy.MM.dd", startTimestamp)
        .toString() + " - " + DateFormat.format("MM.dd", endTimestamp).toString()
}

// FCM 메시지로 사용(사용자에게 하루전날 예약알림)
fun convertTimeToUserStartFcmMessage(date: Long, time: String): String =
    date.convertTimestampToDate() + " " + time + " 여행 하루 전날입니다."

// FCM 메시지로 사용(이장님꼐 사용자의 예약알림)
fun convertTimeToMasterFcmMessage(date: Long): String =
    date.convertTimestampToDate() + "에 고객 예약이 있습니다."

// FCM 메시지로 사용(이장님수락)
fun convertTimeToMasterAcceptFcmMessage(date: Long, time: String): String =
    date.convertTimestampToDate() + " " + time + " 예약을 이장님이 수락했습니다."

// FCM 메시지로 사용(이장님거절)
fun convertTimeToMasterDenyFcmMessage(date: Long, time: String): String =
    date.convertTimestampToDate() + " " + time + " 예약을 이장님이 취소했습니다."

// FCM 메시지로 사용(사용자거절)
fun convertTimeToUserDenyFcmMessage(date: Long): String =
    date.convertTimestampToDate() + " 예약을 사용자가 취소했습니다."

fun combineTimestamp(x: Long, y: Long) = (x.toString() + y.toString()).toLong()

// 랜덤키값
fun getRandomKey(): Long = Random(System.currentTimeMillis()).nextLong(100000, 999999)

// 타임스탬프
fun getTimestamp(): Long = System.currentTimeMillis()

 

 

 

 

 

이미지, 색 세팅 호환버전

import android.content.Context
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat

fun Context.getMyDrawable(id: Int): Drawable? {
    return ContextCompat.getDrawable(this, id)
}

fun Context.getMyColor(id: Int): Int {
    return ContextCompat.getColor(this, id)
}

 

 

 

객체 <-> Map 변환

package com.mtjin.lolrankduo.utils.extensions

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

val gson = Gson()

fun <T> T.serializeToMap(): HashMap<String, Any> {
    return convert()
}

//convert a map to a data class
inline fun <reified T> HashMap<String, Any>.toDataClass(): T {
    return convert()
}

//convert an object of type I to type O
inline fun <I, reified O> I.convert(): O {
    val json = gson.toJson(this)
    return gson.fromJson(json, object : TypeToken<O>() {}.type)
}

 


 

 

[바인딩어댑터]

 

 

어댑터 세팅, 무한스크롤, 이미지세팅, 레이팅바 점수, 날짜(타임스탬프)관련 등이 있습니다. 

package com.mtjin.nomoneytrip.views

import android.os.Build
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.text.HtmlCompat
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.mtjin.nomoneytrip.R
import com.mtjin.nomoneytrip.data.alarm.Alarm
import com.mtjin.nomoneytrip.data.community.UserReview
import com.mtjin.nomoneytrip.data.home.Product
import com.mtjin.nomoneytrip.data.local_page.TourIntroduce
import com.mtjin.nomoneytrip.data.master_main.MasterProduct
import com.mtjin.nomoneytrip.data.master_write.MasterLetter
import com.mtjin.nomoneytrip.data.reservation_history.ReservationProduct
import com.mtjin.nomoneytrip.utils.*
import com.mtjin.nomoneytrip.utils.extensions.*
import com.mtjin.nomoneytrip.views.alarm.AlarmAdapter
import com.mtjin.nomoneytrip.views.community.CommunityAdapter
import com.mtjin.nomoneytrip.views.favorite.FavoriteAdapter
import com.mtjin.nomoneytrip.views.home.HomeHashTagAdapter
import com.mtjin.nomoneytrip.views.home.HomeProductAdapter
import com.mtjin.nomoneytrip.views.home.ProductHashTagAdapter
import com.mtjin.nomoneytrip.views.localpage.LocalPageAdapter
import com.mtjin.nomoneytrip.views.localpage.LocalProductAdapter
import com.mtjin.nomoneytrip.views.master_main.MasterMainAdapter
import com.mtjin.nomoneytrip.views.profile.ProfileMasterLetterAdapter
import com.mtjin.nomoneytrip.views.reservation_history.ReservationHistoryAdapter
import com.mtjin.nomoneytrip.views.tour_history.TourHistoryAdapter
import de.hdodenhof.circleimageview.CircleImageView
import java.util.concurrent.TimeUnit
import kotlin.math.roundToInt

@BindingAdapter("urlImage")
fun ImageView.setUrlImage(url: String) {
    Glide.with(this).load(url)
        .thumbnail(0.1f)
        .error(R.drawable.img_product)
        .into(this)
}

@BindingAdapter("urlImageRadius16")
fun ImageView.setUrlImageRadius16(url: String) {
    Glide.with(this).load(url)
        .thumbnail(0.1f)
        .transform(RoundedCorners(16))
        .into(this)
}

@BindingAdapter("htmlText")
fun TextView.setHtmlText(html: String?) {
    text = html?.let { HtmlCompat.fromHtml(it, HtmlCompat.FROM_HTML_MODE_COMPACT) }
}

@BindingAdapter("alarmStateImage")
fun CircleImageView.setReadState(readState: Boolean) {
    if (readState) setImageDrawable(context.getMyDrawable(R.drawable.ic_alarm_pic))
    else setImageDrawable(context.getMyDrawable(R.drawable.ic_alarm_pic_2))

}

@BindingAdapter("alarmBackground")
fun View.setAlarmBackground(readState: Boolean) {
    if (readState) setBackgroundColor(context.getMyColor(R.color.colorWhiteFDFD))
    else setBackgroundColor(context.getMyColor(R.color.colorWhiteFFF5EF))
}

@BindingAdapter("masterState")
fun View.setMasterState(masterState: Int) {
    if (masterState != 0) visibility = View.GONE
    else visibility = View.VISIBLE
}

//예약취소 보이기 유무
@BindingAdapter("reservationVisibility")
fun TextView.setReservationVisibility(reservationProduct: ReservationProduct) {
    when {
        reservationProduct.reservation.state == 3 -> { //사용자 취소한 경우
            visibility = View.GONE
        }
        reservationProduct.reservation.state == 1 -> { //이장님 거절한 경우
            visibility = View.GONE
        }
        reservationProduct.reservation.state == 2 && reservationProduct.reservation.startDateTimestamp >= getTimestamp() -> {//이장님 수락하고 아직 여행전인 경우
            visibility = View.VISIBLE
        }
        reservationProduct.reservation.endDateTimestamp < getTimestamp() -> { //이미 여행 끝난 경우
            visibility = View.GONE
        }
        else -> {
            visibility = View.VISIBLE
        }
    }
}

//예약상태별 텍스트
@BindingAdapter("reservationStateText")
fun TextView.setReservationStateText(reservationProduct: ReservationProduct) {
    when {
        reservationProduct.reservation.state == 3 -> { //사용자 취소한 경우
            text = "예약이 취소되었습니다."
            setTextColor(context.getMyColor(R.color.colorRedEF4550))
        }
        reservationProduct.reservation.state == 1 -> { //이장님 거절한 경우
            text = "이장님이 예약을 거절했습니다."
            setTextColor(context.getMyColor(R.color.colorRedEF4550))
        }
        reservationProduct.reservation.state == 2 && reservationProduct.reservation.startDateTimestamp >= getTimestamp() -> {//이장님 수락하고 아직 여행전인 경우
            text = "예약이 확정되었습니다."
            setTextColor(context.getMyColor(R.color.colorOrangeF79256))
        }
        reservationProduct.reservation.endDateTimestamp < getTimestamp() -> { //이미 여행 끝난 경우
            text = "다녀온 여행입니다."
            setTextColor(context.getMyColor(R.color.colorOrangeF79256))
        }
        else -> {
            text = "예약 승인을 기다리고 있습니다."
            setTextColor(context.getMyColor(R.color.colorOrangeF79256))
        }
    }
}

@BindingAdapter("rating")
fun RatingBar.setMovieRating(score: String) {
    rating = (score.toFloatOrNull() ?: 0f)
}

@BindingAdapter("ratingListAverage")
fun RatingBar.setRatingListAverage(ratingList: List<Float>) {
    rating = if (ratingList.isNotEmpty()) {
        val average = ratingList.sum() / ratingList.size
        val score: Float = ((average * 10.0).roundToInt() / 10.0).toFloat()
        score
    } else {
        0f
    }
}

@BindingAdapter("ratingListAverageText")
fun TextView.setRatingListAverageText(ratingList: List<Float>) {
    text = if (ratingList.isNotEmpty()) {
        val average = ratingList.sum() / ratingList.size
        val score = ((average * 10.0).roundToInt() / 10.0).toString()
        score
    } else {
        "" + 0
    }
}

// num -> 외 1명, 1명일 경우는 안보이게
@BindingAdapter("numHowManyExceptMe")
fun TextView.setNumHowManyExceptMe(num: String) {
    if (num == "1" || num == "0") {
        visibility = View.GONE
    } else {
        visibility = View.VISIBLE
        text = ("외 " + num + "명")
    }
}


//9.6~9.8
@BindingAdapter("startTimestampTerm", "endTimestampTerm")
fun TextView.setTimestampTerm(startTimestamp: Long, endTimestamp: Long) {
    text = convertTimestampToTerm(startTimestamp, endTimestamp)
}

//09.06 - 09.08
@BindingAdapter("startTimestampOnlyDateMinusTerm", "endTimestampOnlyDateMinusTerm")
fun TextView.setTimestampOnlyDateMinusTerm(startTimestamp: Long, endTimestamp: Long) {
    text = convertTimestampOnlyDateMinusTerm(startTimestamp, endTimestamp)
}

//timestamp -> 2020.01.02
@BindingAdapter("timestampPointFullDate")
fun TextView.setTimestampPointFullDate(timestamp: Long) {
    text = timestamp.convertTimestampToPointFullDate()
}

//timestamp -> 01.02
@BindingAdapter("timestampSlashOnlyDate")
fun TextView.setTimestampPointOnlyDate(timestamp: Long) {
    text = timestamp.convertTimestampToSlashOnlyDate()
}

//timestamp -> 2020.01.02 23:00
@BindingAdapter("timestampPointFullDateTime")
fun TextView.setTimestampPointFullDateTime(timestamp: Long) {
    text = timestamp.convertTimestampToPointFullDateTime()
}

// timestamp(1599663600000), time(일손 4시간) -> 2박, 일손 8시간
@BindingAdapter("startTimestamp", "endTimestamp", "time")
fun TextView.setDayTime(startTimestamp: Long, endTimestamp: Long, time: String) {
    var time1 = startTimestamp
    var time2 = endTimestamp
    val MILLIS_PER_DAY = 1000 * 60 * 60 * 24.toLong()
    time1 -= time1 % MILLIS_PER_DAY
    time2 -= time2 % MILLIS_PER_DAY
    val day = TimeUnit.DAYS.convert(time2 - time1, TimeUnit.MILLISECONDS).toString()
    text = (day + "박, " + time)
}

// timestamp(1599663600000) -> 2박
@BindingAdapter("startTimestampNight", "endTimestampNight")
fun TextView.setTimestampNight(startTimestamp: Long, endTimestamp: Long) {
    var time1 = startTimestamp
    var time2 = endTimestamp
    val MILLIS_PER_DAY = 1000 * 60 * 60 * 24.toLong()
    time1 -= time1 % MILLIS_PER_DAY
    time2 -= time2 % MILLIS_PER_DAY
    val day = TimeUnit.DAYS.convert(time2 - time1, TimeUnit.MILLISECONDS).toString()
    text = (day + "박")
}

// 하단 다음버튼 필수선택 여부에 따른 배경 색
@BindingAdapter("onNextBackground")
fun TextView.setOnNextBackground(isCompleted: Boolean) {
    if (isCompleted) setBackgroundColor(context.getMyColor(R.color.colorOrangeF79256))
    else setBackgroundColor(context.getMyColor(R.color.colorGrayC8C8))
}

// 인증하기 배경색
@RequiresApi(Build.VERSION_CODES.O)
@BindingAdapter("onRequestBackground")
fun TextView.setOnRequestBackground(isCompleted: Boolean) {
    if (isCompleted) {
        background = context.getMyDrawable(R.drawable.bg_btn_solid_orange_f792_radius_8dp)
    } else context.getMyDrawable(R.drawable.bg_btn_solid_gray_c8c8_radius_8dp)
}

// 인증하기 화면 인증번호 입력 EditText
@BindingAdapter("onEnterBackground")
fun EditText.setOnEnterBackground(isCompleted: Boolean) {
    background =
        if (isCompleted) context.getMyDrawable(R.drawable.bg_edit_stroke_gray_c8c8_radius_2dp)
        else context.getMyDrawable(R.drawable.bg_edit_solid_gray_f4f4_radius_2dp)
}

@BindingAdapter("setItems")
fun RecyclerView.setAdapterItems(items: List<Any>?) {
    when (adapter) {
        is LocalPageAdapter -> {
            items?.let {
                with(adapter as LocalPageAdapter) {
                    clear()
                    addItems(it as List<TourIntroduce>)
                }
            }
        }
        is HomeProductAdapter -> {
            items?.let {
                with(adapter as HomeProductAdapter) {
                    clear()
                    addItems(it as List<Product>)
                }
            }
        }
        is ProductHashTagAdapter -> {
            items?.let {
                with(adapter as ProductHashTagAdapter) {
                    clear()
                    addItems(it as List<String>)
                }
            }
        }
        is HomeHashTagAdapter -> {
            items?.let {
                with(adapter as HomeHashTagAdapter) {
                    clear()
                    addItems(it as List<String>)
                }
            }
        }
        is LocalProductAdapter -> {
            items?.let {
                with(adapter as LocalProductAdapter) {
                    clear()
                    addItems(it as List<Product>)
                }
            }
        }
        is ReservationHistoryAdapter -> {
            items?.let {
                with(adapter as ReservationHistoryAdapter) {
                    clear()
                    addItems(it as List<ReservationProduct>)
                }
            }
        }
        is TourHistoryAdapter -> {
            items?.let {
                with(adapter as TourHistoryAdapter) {
                    clear()
                    addItems(it as List<ReservationProduct>)
                }
            }
        }
        is CommunityAdapter -> {
            items?.let {
                with(adapter as CommunityAdapter) {
                    clear()
                    addItems(it as List<UserReview>)
                }
            }
        }
        is AlarmAdapter -> {
            items?.let {
                with(adapter as AlarmAdapter) {
                    clear()
                    addItems(it as List<Alarm>)
                }
            }
        }
        is MasterMainAdapter -> {
            items?.let {
                with(adapter as MasterMainAdapter) {
                    clear()
                    addItems(it as List<MasterProduct>)
                }
            }
        }
        is FavoriteAdapter -> {
            items?.let {
                {
                    with(adapter as FavoriteAdapter) {
                        clear()
                        addItems(it as List<Product>)
                    }
                }
            }
        }
        is ProfileMasterLetterAdapter -> {
            items?.let {
                {
                    with(adapter as ProfileMasterLetterAdapter) {
                        clear()
                        addItem(
                            MasterLetter(
                                title = "무전일기 이장",
                                timestamp = getTimestamp(),
                                content = "반갑습니다! 안전하고 멋진\n" +
                                        "무전여행을 기대할게요 :)"
                            )
                        )
                        addItems(it as List<MasterLetter>)
                    }
                }
            }
        }
        else -> {
            Log.d(TAG, "바인딩어댑터 setItems 예외 에러")
        }

    }
}

 

 

 

package com.mtjin.cnunoticeapp.views

import android.widget.TextView
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.mtjin.cnunoticeapp.data.bachelor.BachelorNotice
import com.mtjin.cnunoticeapp.data.board_list.Board
import com.mtjin.cnunoticeapp.data.business.BusinessNotice
import com.mtjin.cnunoticeapp.data.employ.EmployNotice
import com.mtjin.cnunoticeapp.data.favorite.FavoriteNotice
import com.mtjin.cnunoticeapp.data.general.GeneralNotice
import com.mtjin.cnunoticeapp.utils.EndlessRecyclerViewScrollListener
import com.mtjin.cnunoticeapp.utils.extensions.convertBoardTime
import com.mtjin.cnunoticeapp.views.bachelor.BachelorAdapter
import com.mtjin.cnunoticeapp.views.bachelor.BachelorNoticeViewModel
import com.mtjin.cnunoticeapp.views.board_list.BoardAdapter
import com.mtjin.cnunoticeapp.views.board_list.BoardListViewModel
import com.mtjin.cnunoticeapp.views.business.BusinessAdapter
import com.mtjin.cnunoticeapp.views.business.BusinessNoticeViewModel
import com.mtjin.cnunoticeapp.views.employ.EmployAdapter
import com.mtjin.cnunoticeapp.views.employ.EmployNoticeViewModel
import com.mtjin.cnunoticeapp.views.employ.FavoriteAdapter
import com.mtjin.cnunoticeapp.views.general.GeneralAdapter
import com.mtjin.cnunoticeapp.views.general.GeneralNoticeViewModel

@BindingAdapter("setBoardTime")
fun TextView.setBoardTime(timestamp: Long) {
    text = timestamp.convertBoardTime()
}

@BindingAdapter("setBachelorItems")
fun RecyclerView.setBachelorAdapterItems(items: List<BachelorNotice>?) {
    with((adapter as BachelorAdapter)) {
        this.clear()
        items?.let { this.addItems(it) }
    }
}

@BindingAdapter("setGeneralItems")
fun RecyclerView.setGeneralAdapterItems(items: List<GeneralNotice>?) {
    with((adapter as GeneralAdapter)) {
        this.clear()
        items?.let { this.addItems(it) }
    }
}

@BindingAdapter("setBusinessItems")
fun RecyclerView.setBusinessAdapterItems(items: List<BusinessNotice>?) {
    with((adapter as BusinessAdapter)) {
        this.clear()
        items?.let { this.addItems(it) }
    }
}

@BindingAdapter("setEmployItems")
fun RecyclerView.setEmployAdapterItems(items: List<EmployNotice>?) {
    with((adapter as EmployAdapter)) {
        this.clear()
        items?.let { this.addItems(it) }
    }
}

@BindingAdapter("setFavoriteItems")
fun RecyclerView.setFavoriteAdapterItems(items: List<FavoriteNotice>?) {
    with((adapter as FavoriteAdapter)) {
        this.clear()
        items?.let { this.addItems(it) }
    }
}

@BindingAdapter("setBoardItems")
fun RecyclerView.setBoardAdapterItems(items: List<Board>?) {
    with((adapter as BoardAdapter)) {
        this.clear()
        items?.let { this.addItems(it) }
    }
}

@BindingAdapter("bachelorEndlessScroll")
fun RecyclerView.setBachelorEndlessScroll(
    viewModel: BachelorNoticeViewModel
) {
    val scrollListener =
        object : EndlessRecyclerViewScrollListener(layoutManager as LinearLayoutManager) {
            override fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?) {
                viewModel.requestMoreNotice(totalItemsCount + 1)
            }
        }
    this.addOnScrollListener(scrollListener)
}

@BindingAdapter("generalEndlessScroll")
fun RecyclerView.setGeneralEndlessScroll(
    viewModel: GeneralNoticeViewModel
) {
    val scrollListener =
        object : EndlessRecyclerViewScrollListener(layoutManager as LinearLayoutManager) {
            override fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?) {
                viewModel.requestMoreNotice(totalItemsCount + 1)
            }
        }
    this.addOnScrollListener(scrollListener)
}

@BindingAdapter("businessEndlessScroll")
fun RecyclerView.setBusinessEndlessScroll(
    viewModel: BusinessNoticeViewModel
) {
    val scrollListener =
        object : EndlessRecyclerViewScrollListener(layoutManager as LinearLayoutManager) {
            override fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?) {
                viewModel.requestMoreNotice(totalItemsCount + 1)
            }
        }
    this.addOnScrollListener(scrollListener)
}

@BindingAdapter("employEndlessScroll")
fun RecyclerView.setEmployEndlessScroll(
    viewModel: EmployNoticeViewModel
) {
    val scrollListener =
        object : EndlessRecyclerViewScrollListener(layoutManager as LinearLayoutManager) {
            override fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?) {
                viewModel.requestMoreNotice(totalItemsCount + 1)
            }
        }
    this.addOnScrollListener(scrollListener)
}

@BindingAdapter("boardEndlessScroll")
fun RecyclerView.setBoardEndlessScroll(
    viewModel: BoardListViewModel
) {
    val scrollListener =
        object : EndlessRecyclerViewScrollListener(layoutManager as LinearLayoutManager) {
            override fun onLoadMore(page: Int, totalItemsCount: Int, view: RecyclerView?) {
                viewModel.requestBoards(totalItemsCount + 10)
            }
        }
    this.addOnScrollListener(scrollListener)
}

 

 

 

728x90
Comments