我在我的应用程序中使用导航组件,使用Retrofit在MVVM架构中获取api数据并在嵌套的RecyclerView中显示。这个过程可以很好地工作,并且没有在嵌套的RecyclerView中显示数据时出现问题,但是当进入详细信息片段并返回到先前的片段时,无法保存状态和位置项在水平列表中,如何可以在返回到先前的片段时显示当前位置的RecyclerView?
父适配器
import kotlinx.android.synthetic.main.item_main_shaping_group.view.*
class MainShapingAdapter(
private val listGroup: MutableList<MainModel>,
private val listener: ListItemClick
) : RecyclerView.Adapter<MainShapingAdapter.MyViewHolder>(),
MainShapingChildAdapter.ListItemClickChild {
private val viewPool = RecyclerView.RecycledViewPool()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val layout = LayoutInflater.from(parent.context)
.inflate(R.layout.item_main_shaping_group, parent, false)
return MyViewHolder(layout)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.itemView.apply {
tv_titleGroup_itemGroup.text = listGroup[position].category.categoryTitle
rv_itemGroup.layoutManager =
LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, true)
rv_itemGroup.adapter = MainShapingChildAdapter(
listGroup[position].listProduct.toMutableList(),
this@MainShapingAdapter
)
rv_itemGroup.isNestedScrollingEnabled = false
rv_itemGroup.setRecycledViewPool(viewPool)
btn_more_itemGroup.setOnClickListener {
listener.itemOnclickCategory(listGroup[position].category)
}
}
}
override fun getItemCount(): Int = listGroup.size
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
}
interface ListItemClick {
fun itemOnclickCategory(category: CategoryModel)
fun itemOnclickChild(product: Product)
}
override fun childOnclick(product: Product) {
listener.itemOnclickChild(product)
}
override fun onViewRecycled(holder: MyViewHolder) {
super.onViewRecycled(holder)
Log.d(ConstantApp.TAG, "onViewRecycled 1")
}
}
子适配器
import kotlinx.android.synthetic.main.item_main_shaping_child.view.*
class MainShapingChildAdapter(
private val listProduct: MutableList<Product>,
private val listener: ListItemClickChild
) : RecyclerView.Adapter<MainShapingChildAdapter.MyViewHolder>() {
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val layout = LayoutInflater.from(parent.context)
.inflate(R.layout.item_main_shaping_child, parent, false)
return MyViewHolder(layout)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.itemView.apply {
Glide.with(context).load(listProduct[position].productCover)
.into(iv_coverProduct_shapingChild)
tv_titleProduct_shapingChild.text = listProduct[position].productTitle
tv_priceProduct_shapingChild.text = listProduct[position].productPrice.toString()
setOnClickListener {
listener.childOnclick(listProduct[position])
}
}
}
override fun getItemCount(): Int = listProduct.size
interface ListItemClickChild {
fun childOnclick(product: Product)
}
}