본문 바로가기

개발일기

23.11.8 개발일기 fab 버튼 CalendarViewModel 활용

<vector android:height="24dp" android:tint="#FFFFFF"
    android:viewportHeight="24" android:viewportWidth="24"
    android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="@android:color/white" android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

 

fab 액션버튼 벡터코드

 

 

class CalendarViewModel : ViewModel() {
    // 뷰모델 내에서만 변경 가능한 MutableLiveData를 사용하여 리스트 관리
    private val _list: MutableLiveData<List<CalendarModel>> = MutableLiveData()
    val list: LiveData<List<CalendarModel>> get() = _list // 읽기 전용 리스트

    // 날짜를 선택했을 때 해당 날짜의 메모들만 가지고 있는 리스트
    private val _dateList: MutableLiveData<List<CalendarModel>?> = MutableLiveData()
    val dateList: MutableLiveData<List<CalendarModel>?> get() = _dateList // 읽기 전용 리스트

    // 선택한 날짜에 해당하는 메모들만 _dateList에 저장
    fun setCalendarDate(date: CalendarDay) {
        val filterData = list.value?.filter { memoItem ->
            memoItem.day == date.day && memoItem.month == date.month && memoItem.year == date.year
        }
        _dateList.value = filterData
    }

    // 새로운 메모를 _list에 추가
    fun addMemoItem(model: CalendarModel) {
        val currentList = list.value.orEmpty().toMutableList()
        currentList.add(model)
        _list.value = currentList
    }

    // 특정 위치에 있는 메모를 _list에서 삭제
    fun removeMemoItem(model: CalendarModel, position: Int) {
        val currentList = list.value.orEmpty().toMutableList()
        currentList.removeAt(position)
        _list.value = currentList
    }

    // 특정 메모를 수정
    fun editMemoItem(model: CalendarModel) {
        val currentList = list.value.orEmpty().toMutableList()
        val index = currentList.indexOfFirst { it.id == model.id }
        if (index != -1) {
            currentList[index] = model
            _list.value = currentList
        }
    }
}