RecyclerView最初不绑定数据

时间:2018-07-24 16:02:55

标签: android android-recyclerview kotlin recycler-adapter

我使用RecyclerView显示项目列表。我尝试使用标准的RecyclerView而不是我自己的类,问题是相同的。

我的问题是,当片段最初加载时,它似乎没有将数据映射到每个布局项目,因此,我只用铅笔就可以得到这些胖块,如图像视图顶部所示。 如果向下滚动,则会得到正确的布局,其中显示了数据,如图像底部所示。 如果我向下滚动到足以隐藏“错误”项的位置,然后再备份,它们将使用正确的数据正确呈现。

example

该视图是ConstraintLayout中的以下XML。

<x.y.z.EmptyStateRecyclerView
    android:id="@+id/customer_list"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:scrollbars="vertical"
    app:layoutManager="android.support.v7.widget.LinearLayoutManager"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:listitem="@layout/customer_item" />

这是课程。

class EmptyStateRecyclerView : RecyclerView {
  constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
  constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
    context,
    attrs,
    defStyle
  )

  var emptyView: View? by Delegates.observable<View?>(null) { _, _, _ -> updateState() }

  private fun updateState() {
    if (emptyView != null && adapter != null) {
      val empty = adapter.itemCount == 0
      visibility = if (!empty) VISIBLE else GONE
      emptyView?.visibility = if (empty) VISIBLE else GONE
    }
  }

  private val observer = object : AdapterDataObserver() {
    override fun onChanged() {
      updateState()
    }
  }

  override fun setAdapter(a: Adapter<*>?) {
    adapter?.unregisterAdapterDataObserver(observer)
    super.setAdapter(a)
    adapter?.registerAdapterDataObserver(observer)
    updateState()
  }
}

0 个答案:

没有答案
相关问题