我正在使用MergeAdapter(又称ConcatAdapter)
https://medium.com/androiddevelopers/merge-adapters-sequentially-with-mergeadapter-294d2942127a
但是我需要做的是第一个Adapter应该显示gridlayout,第二个Adapter应该显示linearlayout,所以,如果我这样做的话

 val headerAdapter = HeaderAdapter(requireContext(), Header("TestHeader"))
        val dividerViewAdapter = DividerViewAdapter(requireContext())
        val animalAdapter = DividerViewAdapter(requireContext(),DataSource.animalList) // -> this should be shown as a GridLayout
        val mergeAdapter = MergeAdapter(headerAdapter,dividerViewAdapter,animalAdapter)
        test_rv.layoutManager = LinearLayoutManager(requireContext())
        test_rv.adapter = mergeAdapter
现在,此代码可以正常工作,但是由于它具有linearlayoutmanager,因此所有内容将显示为LinearLayout,其中我的animalAdapter不会按我的意愿显示。
无论如何,是否需要为不同的适配器设置不同的布局管理器以我想要的方式显示数据?

最佳答案

其实这是我解决的方法:

    class HorizontalContainerAdapter(private val lifecycleOwner: LifecycleOwner, val adapter : ListAdapter<*, *>) :
ListAdapter<String, HorizontalContainerAdapter.Holder>(diffCallback) {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
    val inflater = LayoutInflater.from(parent.context)
    return Holder(DataBindingUtil.inflate(inflater, R.layout.item_horizontal_container, parent, false), adapter)
}

override fun onBindViewHolder(holder: Holder, position: Int) {
    holder.binding.lifecycleOwner = lifecycleOwner
}

override fun getItemViewType(position: Int): Int {
    return R.layout.item_horizontal_container
}

override fun getItemCount(): Int {
     return 1
}

class Holder(val binding: ItemHorizontalContainerBinding, adapter: ListAdapter<*, *>) : RecyclerView.ViewHolder(binding.root) {

    init {
        binding.recyclerView.layoutManager = LinearLayoutManager(binding.recyclerView.context, LinearLayoutManager.HORIZONTAL, false)
        binding.recyclerView.adapter = adapter
    }
}

companion object {
    val diffCallback by lazy {
        object :
            DiffUtil.ItemCallback<String>() {

            override fun areItemsTheSame(oldItem: String, newItem: String): Boolean {
                return oldItem == newItem
            }

            override fun areContentsTheSame(oldItem: String, newItem: String): Boolean {
                return oldItem == newItem
            }
        }
    }
}
Mergeadapter / ConcatAdapter with Horizontal and Vertical Layouts
祝你好运

07-26 09:42