I have a vertical recyclerview with 4 different types of views, each view has a horizontal recyclerview. My problem is that the main thread gets stuck for 5 seconds or so when loading everything, and looking at the layoutmanager I discovered that it is loading all the items from the vertical recyclerview and all those from a horizontal recyclerview. I read that this can happen when the view being inflated is very complex, but can I manage it somehow so that it doesn't load all at once or at least doesn't block the main thread?
this is my home fragment
class HomeFragment : Fragment(R.layout.fragment_home) {
private lateinit var binding: FragmentHomeBinding
private val viewModel by viewModels<CustomerViewModel> {
CustomerViewModelFactory(ApiCallsRepositoryImpl(DataSource(RetrofitClient.webservice)))
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentHomeBinding.bind(view)
//local json to test home
LoadDataHome()
}
private fun LoadDataHome() {
val jsonString = readJsonFile(binding.root.context)
val gson = Gson()
val homeResponse = gson.fromJson(jsonString, HomeResponse::class.java)
val itemlist1 = mutableListOf<HomeResponseItem>()
itemlist1.addAll(homeResponse)
val adapterPrincipal = HomeResponseAdapter(itemlist1)
binding.rvPrincipal.layoutManager =
LinearLayoutManager(binding.root.context, RecyclerView.VERTICAL, false)
binding.rvPrincipal.adapter = adapterPrincipal
adapterPrincipal.notifyDataSetChanged()
}
private fun readJsonFile(context: Context): String {
val inputStream = context.resources.openRawResource(R.raw.json_home)
val size = inputStream.available()
val buffer = ByteArray(size)
inputStream.read(buffer)
inputStream.close()
return String(buffer, Charset.defaultCharset())
}
}
HomeResponseAdapter.kt
class HomeResponseAdapter(private var itemList: List<HomeResponseItem>) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return GetHomeResponseViewHolder().get(viewType, parent)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val item = itemList[position]
BindHomeResponse().Bind(holder, item)
}
override fun getItemViewType(position: Int): Int {
return when (itemList[position].idContenido) {
"SquareBanners" -> 4
"PillButtons" -> 1
"MiniBanners" -> 3
"Productos" -> 2
else -> 5
}
}
override fun getItemCount(): Int {
return itemList.size
}
}
what am i missing?