Issue
supposeI have such a fragment.
class MyFragment : Fragment() {
// Suppose there is a binding, which contains a recyclerView
private var _binding: FragmentAbinding? = null
val binding get() = _binding!!
// Suppose there is a recyclerView adapter
val adapter by lazy { MyAdapter() }
// use navigation as router
private val navController: NavController by lazy { findNavController() }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentAbinding.inflate(
inflater,
container,
false
)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// ...
binding.recyclerView.adapter = adapter
// ...
}
override fun onDestroyView() {
_binding = null
}
}
when using navController.navigate(...), MyFragment will be replaced, and _binding will be null. However, since recyclerView uses the observer mode to observe the dataset in the adapter, the adapter will hold recyclerView as its observer. After navigating to another fragment(that is, after onDestroyView()), will recyclerView actively cancel the observation of the adapter dataset, which means that adapter would not hold an instance of recyclerView?
I use method below to remove adapter dataset observers
fun RecyclerView.Adapter<*>.removeObservers() {
var clazz: Class<*> = javaClass
val simpleName = RecyclerView.Adapter::class.simpleName
while (clazz.simpleName != simpleName) {
clazz = clazz.superclass
}
val field = clazz.getDeclaredField("mObservable")
field.isAccessible = true
val observable = field[this] as Observable<*>
observable.unregisterAll()
}
// in fragment
class MyFragment : Fragment() {
override fun onDestroyView() {
adapter.removeObservers()
}
}
Solution
The adapter when called "onCreateViewHolder" uses recyclerView as a view group when you navigate with navigation your fragment just views destroyed but still its instance is alive in the backstack and your adapter is too because that is a class-level variable for solving this issue you should create adapter in view lifecycle events(onViewCreated.. onDestroyView).
Answered By - Pejman Azad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.