본문 바로가기

Study/Android

FragmentStateAdapter

class FragmentPageAdapter(fragment: Fragment): FragmentStateAdapter(fragment) {

    override fun getItemCount(): Int = 2

    override fun createFragment(position: Int): Fragment {
        return when(position) {
            0 -> ReceivedFragment()
            1 -> SentFragment()
            else -> ReceivedFragment()
        }
    }
}

 

ReceiveFragment.kt

class ReceivedFragment : BaseFragment<FragmentReceivedBinding>(R.layout.fragment_received) {

    private val viewModel by activityViewModels<ActiveViewModel>()

    override fun setupObserve() {
        viewModel.receivedList()

        observeViewModel()
    }

    private fun observeViewModel() {
        viewModel.receivedListData.observe(this, {
            when(it.status) {
                ResponseStatus.SUCCESS -> {
                    CLog.i("ReceivedFragment SUCCESS")
                    CLog.i("ReceivedFragment ${it.data.toString()}")
//                    binding.log.text = it.data.toString()
                }
                ResponseStatus.ERROR -> {
                    CLog.i("ReceivedFragment error ${it.message}")
                }
                ResponseStatus.LOADING -> {}
            }
        })
    }
}

 

SentFragment.kt

class SentFragment : BaseFragment<FragmentSentBinding>(R.layout.fragment_sent) {

    private val viewModel by activityViewModels<ActiveViewModel>()

    override fun setupObserve() {
        // 일단 보낸 메시지 확인
        viewModel.sentList()

        observeViewModel()
    }

    private fun observeViewModel() {
        viewModel.sentListData.observe(this, {
            when(it.status) {
                ResponseStatus.SUCCESS -> {
                    CLog.i("SentListData SUCCESS")
                    CLog.i("SentListData ${it.data.toString()}")
//                    binding.log.text = it.data.toString()
                }
                ResponseStatus.ERROR -> {
                    CLog.i("SentListData error ${it.message}")
                }
                ResponseStatus.LOADING -> {}
            }
        })
    }
}