|
| 1 | +package com.hoc.mergeadapter_sample |
| 2 | + |
| 3 | +import android.os.Bundle |
| 4 | +import androidx.activity.viewModels |
| 5 | +import androidx.appcompat.app.AppCompatActivity |
| 6 | +import androidx.lifecycle.Observer |
| 7 | +import androidx.recyclerview.widget.LinearLayoutManager |
| 8 | +import androidx.recyclerview.widget.MergeAdapter |
| 9 | +import androidx.recyclerview.widget.RecyclerView |
| 10 | +import com.hoc.mergeadapter_sample.databinding.ActivityMainBinding |
| 11 | +import kotlin.LazyThreadSafetyMode.NONE |
| 12 | + |
| 13 | +class MainActivity : AppCompatActivity() { |
| 14 | + private val vm by viewModels<MainVM>() |
| 15 | + |
| 16 | + private val userAdapter = UserAdapter() |
| 17 | + private val footerAdapter = FooterAdapter(this::onRetry) |
| 18 | + |
| 19 | + private val binding by lazy(NONE) { |
| 20 | + ActivityMainBinding.inflate(layoutInflater) |
| 21 | + } |
| 22 | + |
| 23 | + override fun onCreate(savedInstanceState: Bundle?) { |
| 24 | + super.onCreate(savedInstanceState) |
| 25 | + setContentView(binding.root) |
| 26 | + |
| 27 | + binding.recyclerView.run { |
| 28 | + setHasFixedSize(true) |
| 29 | + val linearLayoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false) |
| 30 | + layoutManager = linearLayoutManager |
| 31 | + adapter = MergeAdapter(userAdapter, footerAdapter) |
| 32 | + addOnScrollListener(object : RecyclerView.OnScrollListener() { |
| 33 | + override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { |
| 34 | + if (dy > 0 |
| 35 | + && linearLayoutManager.findLastVisibleItemPosition() + VISIBLE_THRESHOLD >= linearLayoutManager.itemCount |
| 36 | + ) { |
| 37 | + vm.loadNextPage() |
| 38 | + } |
| 39 | + } |
| 40 | + }) |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + vm.loadingStateLiveData.observe(this, Observer { |
| 45 | + footerAdapter.submitList(it) |
| 46 | + }) |
| 47 | + vm.userLiveData.observe(this, Observer { |
| 48 | + userAdapter.submitList(it) |
| 49 | + }) |
| 50 | + vm.loadNextPage() |
| 51 | + } |
| 52 | + |
| 53 | + private fun onRetry() = vm.retryNextPage() |
| 54 | + |
| 55 | + private companion object { |
| 56 | + private const val VISIBLE_THRESHOLD = 3 |
| 57 | + } |
| 58 | +} |
0 commit comments