I've recently came upon a really strange issue. I had a mapview in my layout which was inflated using databinding. After I added ViewPager2 to my layout I got this issue:
java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class androidx.recyclerview.widget.RecyclerView$SavedState instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/0x1. Make sure other views do not use the same id.
But it happens only when you first open first fragment and go to next one, then press back.
- If I remove mapview from my layout everything works.
- If I remove viewpager2 from my layout everything works.
- If I remove databinding everything works.
It seems it has something to do with view state, but is there anything I could do to address this issue?
Here's a sample fragment code:
class TestFragment(override val layoutRes: Int = R.layout.fragment_test) : BaseFragment() {
lateinit var binding: FragmentTestBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentTestBinding.inflate(inflater, container, false)
setupMap(savedInstanceState)
return binding.root
}
override fun onResume() {
super.onResume()
binding.mapView.onResume()
}
override fun onPause() {
super.onPause()
binding.mapView.onPause()
}
private fun setupMap(savedInstanceState: Bundle?) {
binding.mapView.onCreate(savedInstanceState)
binding.mapView.onResume()
binding.mapView.getMapAsync { }
}
}
Sample layout:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</layout>
To reproduce I have to open another fragment and then press back
**EDIT: ** Seems like moving viewpager in front of mapview also helps, so databinding can still be used.