打开应用程序时如何更新recyclerview?
How to update the recyclerview when opening the app?
我正在寻找 API 中的电影列表,该项目在 MVVM 中,搜索非常完美。但是,当打开应用程序时,用户必须退出并再次打开,列表才能显示结果。如何解决?
在 onStart 中我使用 Observe
override fun onStart() {
super.onStart()
Log.d("TESTE", "onStart")
viewModel.movieList.observe(this, Observer {
Log.d("TAG", "onCreate: $it")
for (i in it.results){
list.add(i)
}
if (page < 66){
page ++
}
})
在恢复中
override fun onResume() {
super.onResume()
val scope = MainScope()
adapter.setDataSet(list)
scope.launch {
viewModel.getAllMovies(page)
viewModel.getAllGenre()
}
val recyclerView : RecyclerView = findViewById(R.id.recycler_vie_movie_list)
val layoutManager = GridLayoutManager(applicationContext, 3, GridLayoutManager.VERTICAL, false)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
您未正确使用 activity 回调。在 onCreate 中白色所有这些代码(如果您使用 Activity 或使用 onViewCreated 如果它是 Fragment)。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.getMovieList() // realize this method in your ViewModel
// and don't forget to set data to your movieList LiveData
val recyclerView : RecyclerView = findViewById(R.id.recycler_vie_movie_list)
val layoutManager = GridLayoutManager(applicationContext, 3, GridLayoutManager.VERTICAL, false)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
viewModel.movieList.observe(this, Observer { list->
adapter.setDataSet(list)
})
在方法 setDataSet 中调用 notifyDataSetChanged()
祝你工作顺利!
我正在寻找 API 中的电影列表,该项目在 MVVM 中,搜索非常完美。但是,当打开应用程序时,用户必须退出并再次打开,列表才能显示结果。如何解决?
在 onStart 中我使用 Observe
override fun onStart() {
super.onStart()
Log.d("TESTE", "onStart")
viewModel.movieList.observe(this, Observer {
Log.d("TAG", "onCreate: $it")
for (i in it.results){
list.add(i)
}
if (page < 66){
page ++
}
})
在恢复中
override fun onResume() {
super.onResume()
val scope = MainScope()
adapter.setDataSet(list)
scope.launch {
viewModel.getAllMovies(page)
viewModel.getAllGenre()
}
val recyclerView : RecyclerView = findViewById(R.id.recycler_vie_movie_list)
val layoutManager = GridLayoutManager(applicationContext, 3, GridLayoutManager.VERTICAL, false)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
您未正确使用 activity 回调。在 onCreate 中白色所有这些代码(如果您使用 Activity 或使用 onViewCreated 如果它是 Fragment)。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.getMovieList() // realize this method in your ViewModel
// and don't forget to set data to your movieList LiveData
val recyclerView : RecyclerView = findViewById(R.id.recycler_vie_movie_list)
val layoutManager = GridLayoutManager(applicationContext, 3, GridLayoutManager.VERTICAL, false)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
viewModel.movieList.observe(this, Observer { list->
adapter.setDataSet(list)
})
在方法 setDataSet 中调用 notifyDataSetChanged()
祝你工作顺利!