引入
implementation 'androidx.activity:activity-ktx:1.1.0'
implementation 'androidx.fragment:fragment-ktx:1.2.5'
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
implementation "com.github.CymChad:BaseRecyclerViewAdapterHelper:3.0.4"
View
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel by viewModels<MainViewModel> { MainViewModelFactory() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
initView()
initData()
}
private fun initData() {
viewModel.getInitData()
val myAdapter2 = MyAdapter2(R.layout.recycler_main)
myAdapter2.loadMoreModule.setOnLoadMoreListener {
Log.d(TAG, "initData: load more data")
binding.rlRefresh.postDelayed({
viewModel.getMoreData()
myAdapter2.loadMoreModule.loadMoreComplete()
}, 1000)
}
viewModel.dataList.observe(this, Observer {
Log.d(TAG, "initData: 数据发生改变")
if (!viewModel.isLoadMore) {
myAdapter2.data = it
binding.rvRecycle.adapter = myAdapter2
binding.rvRecycle.layoutManager =
LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
} else {
myAdapter2.addData(it)
}
})
}
private fun initView() {
binding.rlRefresh.setOnRefreshListener {
Log.d(TAG, "initView: refresh data ")
binding.rlRefresh.postDelayed({
viewModel.getInitData()
binding.rlRefresh.isRefreshing = false
}, 1000)
}
}
}
ViewModel
class MainViewModel(private var repository: MainRepository) : ViewModel() {
var isLoadMore = false
var dataList = MutableLiveData<MutableList<String>>()
private var pageId = 0
fun getInitData() {
isLoadMore = false
pageId = 0
dataList.value = repository.getData(page = pageId)
}
fun getMoreData() {
isLoadMore = true
dataList.value = repository.getData(page = ++pageId)
}
}
@Suppress("UNCHECKED_CAST")
class MainViewModelFactory : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return MainViewModel(MainRepositoryProvider.getInstance()) as T
}
}
Model
interface MainRepository {
fun getData(page: Int): MutableList<String>
}
class MainRepositoryImp : MainRepository {
override fun getData(page: Int): MutableList<String> {
val list = mutableListOf<String>()
for (i in 0..9) {
list.add((i + page * 10).toString())
}
return list
}
}
object MainRepositoryProvider {
fun getInstance(): MainRepository {
return MainRepositoryImp()
}
}
|