在PagedListAdapter中未调用onCreateViewHolder

时间:2019-05-12 09:43:50

标签: android kotlin android-recyclerview fragment recycler-adapter

我有 PagedListAdapater

class TrackedActivityAdapter constructor(diffUtilCallback: DiffUtil.ItemCallback<TrackedActivity>) :
    PagedListAdapter<TrackedActivity, TrackedActivityAdapter.TrackedActivityHolder>(diffUtilCallback) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TrackedActivityHolder {
        val inflater = LayoutInflater.from(parent.context)
        val view = DataBindingUtil.inflate<ActivityItemBinding>(inflater, R.layout.activity_item, parent, false)
        return TrackedActivityHolder(view)
    }

    override fun onBindViewHolder(holder: TrackedActivityHolder, position: Int) {
        getItem(position)?.let { holder.bind(it) }
    }

    class TrackedActivityHolder(var binding: ActivityItemBinding) : RecyclerView.ViewHolder(binding.root) {

        fun bind(trackedActivity: TrackedActivity) {
            binding.activity = trackedActivity
            binding.executePendingBindings()
        }

    }
}

此适配器在其中创建的片段:

class HistoryFragment : DaggerFragment() {
    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val binding = DataBindingUtil.inflate<HistoryFragmentViewBinding>(
            inflater,
            R.layout.history_fragment_view,
            container,
            false
        )
        val historyViewModel = ViewModelProviders.of(this, viewModelFactory).get(HistoryViewModel::class.java)
        val adapter = TrackedActivityAdapter(TrackedActivity.DIFF_CALLBACK)
        binding.trackedActivityRv.adapter = adapter
        binding.trackedActivityRv.layoutManager = LinearLayoutManager(binding.root.context)
        historyViewModel.getTrackedActivities().observe(this,
            Observer<PagedList<TrackedActivity>> { t ->
                adapter.submitList(t)
            })
        binding.executePendingBindings()
        return binding.root
    }
}

在调用adapter.submitList(t)方法之后。什么也没发生,并且不会调用onCreateViewHolder和onBindViewHolder方法,请告诉我可能是有原因,我只是无法理解(

2 个答案:

答案 0 :(得分:0)

您是否尝试过使用HistoryFragmentViewBinding.inflate(inflater)而不是DataBindingUtil.inflate()

我遇到了同样的问题,被困了好几天。原来我只是在最后返回了错误的观点。它不像您的,但可能值得一试。

答案 1 :(得分:0)

我遇到了同样的问题。和你只差一行,代码完全一样。就我而言

recyclerview.setHasFixedSize(true)

已添加。当我删除它时, onCreateViewHolder() 被调用。 所以,我不知道你代码的哪一部分有问题,但也尝试处理这部分。

val adapter = TrackedActivityAdapter(TrackedActivity.DIFF_CALLBACK)
binding.trackedActivityRv.adapter = adapter
binding.trackedActivityRv.layoutManager = LinearLayoutManager(binding.root.context)
binding.executePendingBindings()