코딩 일기장/Android(Kotlin)

[Android/Kotlin] ViewModel 사용해서 Activity 호출하기(startActivity)

minWachya 2022. 7. 15. 15:58
반응형

아래 ui는 한이음:DetectUs 프로젝트 ui 입니다!

 

구현해 볼 것:

Fragment의 button 클릭 시 Activity로 이동하기(startActivity)

(ListBuildingFragment의 플로팅 버튼 클릭 시

BuildingCreateActivity로 이동하기!!)

(==> 사실 Fragment냐 Activity냐는 별로 안 중요함,, startActivity로 Activity를 호출하고 싶은 거임)

여기서 오른쪽 하단의 플로팅 버튼을 클릭해서
여기로 이동할 것이어요

ViewModel에 아직 익숙치 않아서 적어두려 한다^_^;


1. ViewModel에 버튼을 클릭했는지, 안 했는지 상태를 저장할 변수, 함수 생성

package com.example.safetymanagement2022.ui.list_building

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.safetymanagement2022.model.ListBuildingData
import com.example.safetymanagement2022.repository.list_building.ListBuildingRepository
import com.example.safetymanagement2022.ui.common.Event

class ListBuildingViewModel(private val listBuildingRepository: ListBuildingRepository): ViewModel() {
    private val _listBuildingData = MutableLiveData<ListBuildingData>()
    val listBuildingData: LiveData<ListBuildingData> = _listBuildingData

	// 추가
    private val _openCreateBuildingEvent = MutableLiveData<Unit>()
    val openCreateBuildingEvent: LiveData<Unit> get() = _openCreateBuildingEvent

    init {
        loadListBuildingDate()
    }

    private fun loadListBuildingDate() {
        val listBuildingData = listBuildingRepository.getListBuildingData()
        listBuildingData?.let { data ->
            _listBuildingData.value = data
        }
    }
    
    // 추가
    fun openCreateBuilding() {
        _openCreateBuildingEvent.value = Unit
    }
}

 

2. fragment의 xml에 viewmodel 추가하고 onClick 달기

<data>
    <variable
        name="viewmodel"
        type="com.example.safetymanagement2022.ui.list_building.ListBuildingViewModel" />
</data>
android:onClick="@{() -> viewmodel.openCreateBuilding()}"

(전체 코드)

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="viewmodel"
            type="com.example.safetymanagement2022.ui.list_building.ListBuildingViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_list_building"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_marginHorizontal="15dp"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:listitem="@layout/item_list_building" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/btn_create_building"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:layout_marginEnd="20dp"
            android:layout_marginBottom="5dp"
            android:backgroundTint="@color/app_deep_gray"
            android:contentDescription="@string/description_btn_add_building"
            android:onClick="@{() -> viewmodel.openCreateBuilding()}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

 

3. Fragment.kt에서 viewModel연결하고 Activity 호출하는 코드 생성 

package com.example.safetymanagement2022.ui.list_building

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.example.safetymanagement2022.databinding.FragmentListBuildingBinding
import com.example.safetymanagement2022.ui.building_create.BuildingCreateActivity
import com.example.safetymanagement2022.ui.common.MyViewModelFactory

class ListBuildingFragment: Fragment() {
    private lateinit var binding: FragmentListBuildingBinding
    private val viewModel: ListBuildingViewModel by viewModels { MyViewModelFactory(requireContext()) }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentListBuildingBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.lifecycleOwner = viewLifecycleOwner
        // 추가
        binding.viewModel = viewModel
		// 추가
        viewModel.openCreateBuildingEvent.observe(viewLifecycleOwner) {
            openCreateBuilding()
        }
    }

	// 추가
    private fun openCreateBuilding() {
        val intent = Intent(context, BuildingCreateActivity::class.java)
        startActivity(intent)
    }
}
반응형