Home > Mobile >  Recycler View doesn't render fragment on first instance but does on second time
Recycler View doesn't render fragment on first instance but does on second time

Time:10-08

The title of the question might seem to be a little confusing, but I am working on a small project. To separate out the logic for different modules, we decided to use fragments but we need to load a fragment inside a recycler view item.

So, basically, we are loading a fragment inside a recycler view, itemview. The data that is to be shown is totally backend driven. So, the card will load only when the data is available. So, this is the scenario.

What is happening is that we are trying to load that fragment app starts but for first-time users, the card doesn't show, even though all the required methods and API calls are successful and all the view items are loaded. I checked the visibility of the view and it shows visible, just that, it doesn't load on the screen. But after that, if we open the app again after killing the app from recents menu then that card loads.

Anyone has any idea around this ?

CodePudding user response:

You can't put fragment to resyclerView, cause it can leads to memory leaks. A fragment has longer lifecycle than a view and it cant'be reconfigured correct.

Solutions that I can recommend - build your fragment inside your resycler view (view by view).

I am using https://github.com/sockeqwe/AdapterDelegates library for that.

  1. Get data from API

  2. Convert it to models with common interface

  3. Put that models to one list

    private fun adAdvertising(page: Pages<UIContent>) = page.apply {
             addTitleUI()
             addAdCardUI()
             addAdBannerUI()
         }
    

Model can looks like that

data class TitleUI(
    val leagueName: String,
    val eventsCount: Int,
) : UIContent
  1. add it to adapter with different view holders

By this way you can create fragments with different kind of complexity, and it will be correct

Resource you can read:

https://medium.com/@seidalins/delegate-adapters-building-heterogeneous-recyclerviewadapter-877cb7d3c6c0

CodePudding user response:

Bad idea, recycler view is created to use with view, you will have big problem with memory in this case, create custom views for items

  • Related