我有两个片段--第一个片段是课程列表,第二个片段是课程的详细信息。我想从片段1的滚动状态保存回收器视图的状态,但是当我从片段2返回到片段1(带列表)时,列表会滚动到顶部。我的RecyclerView依赖版本是1.2.1,我使用的是:
courseAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
但它并不能按预期工作。视频:https://drive.google.com/file/d/1StvDdrFTezO6LJmrQU5vLrrpF_PHdr28/view?usp=sharing
课程片段:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initializeView()
initializeViewModel()
}
override fun onStart() {
super.onStart()
courseId = arguments?.getInt(COURSE_ID, -1) ?: -1
fetchCourse()
}
private fun fetchCourse() {
courseId?.let {
showLoadingAnimation()
sharedCourseViewModel.fetchCourse(it)
}
}
...
private fun initializeView() {
binding.recyclerView.layoutManager = LinearLayoutManager(context)
binding.errorLayout.tryAgainBtn.setOnClickListener {
fetchCourse()
}
}
...
private fun initializeViewModel() = with(binding) {
showLoadingAnimation()
sharedCourseViewModel.getCourse().observe(viewLifecycleOwner) { course ->
if (course?.id == courseId) {
hideLoadingAnimation()
if (course == null) {
recyclerView.gone()
errorLayout.root.visible()
}
val courseAdapter = initAdapter
courseAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
course?.let {
(activity as ElearningActivity).setToolbarTitle(course.title)
courseAdapter.setItems(course.sections)
recyclerView.adapter = courseAdapter
loadingInterfaceManager.hideError(errorLayout.root, recyclerView)
}
}
}
...
}
private fun initAdapter(): CourseAdapter {
return CourseAdapter {
(activity as BaseChildActivity).navigateToFragment(CourseLessonFragment(), true)
}
}
片段_课程.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lessons_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:animateLayoutChanges="true"
android:fitsSystemWindows="true">
<include
android:id="@+id/error_layout"
layout="@layout/error_try_again_layout"
android:visibility="gone"/>
<include
android:id="@+id/loading_layout"
layout="@layout/loading_layout"
android:visibility="gone"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingVertical="12dp"
android:background="@color/white"
android:visibility="gone"/>
</RelativeLayout>
1条答案
按热度按时间m528fe3b1#
我不确定你在哪里初始化
initAdapter
,以及你是如何提供数据的,但是你可以替换下面提到的代码吗从
至