【发布时间】:2021-03-25 05:26:32
【问题描述】:
我当前的问题是,我的LoadStateAdapter 显示加载和错误状态,不在我的recyclerview 内,它有一个网格布局作为布局管理器。我在官方的 android 开发者网站上没有找到任何关于此的信息,所以我在这里问:如何将我的 LoadStateAdapter 居中在我的 Recyclerview 中?
当前
片段
@AndroidEntryPoint
class ShopFragment : Fragment(R.layout.fragment_shop), ShopAdapter.OnItemClickListener {
private val shopViewModel: ShopViewModel by viewModels()
private val shopBinding: FragmentShopBinding by viewBinding()
@Inject lateinit var shopListAdapter: ShopAdapter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bindObjects()
}
private fun bindObjects() {
shopBinding.adapter = shopListAdapter.withLoadStateFooter(ShopLoadAdapter(shopListAdapter::retry))
shopListAdapter.clickHandler(this)
}
override fun onDestroyView() {
requireView().findViewById<RecyclerView>(R.id.rv_shop).adapter = null
super.onDestroyView()
}
}
适配器
@FragmentScoped
class ShopLoadAdapter(private val retry: () -> Unit): LoadStateAdapter<ShopLoadAdapter.ShopLoadStateViewHolder>() {
inner class ShopLoadStateViewHolder(private val binding: ShopLoadStateFooterBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(loadState: LoadState) {
with(binding) {
shopLoadPb.isVisible = loadState is LoadState.Loading
shopLoadMbtnRetry.isVisible = loadState is LoadState.Error
shopLoadTvError.isVisible = loadState is LoadState.Error
}
}
}
override fun onBindViewHolder(holder: ShopLoadStateViewHolder, loadState: LoadState) = holder.bind(loadState)
override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): ShopLoadStateViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ShopLoadStateFooterBinding.inflate(layoutInflater, parent, false)
return ShopLoadStateViewHolder(binding).also {
binding.shopLoadMbtnRetry.setOnClickListener { retry.invoke() }
}
}
}
布局.xml
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_shop"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/headline"
app:recyclerview_adapter="@{adapter}"
tools:listitem="@layout/shop_list_item"/>
【问题讨论】:
-
我觉得和
setSpanSizeLookup有关你可以查stackoverflow.com/questions/63509661/… -
这对我有什么帮助?我知道
LoadStateAdapter始终是我recylerview 中的最后一项,所以我必须将我的最后一项的跨度大小设置为与其他项不同,对吗?但是这里的问题是有时 LoadStateAdapter 没有显示,因为没有错误或加载状态等。 -
应该是分页库的问题。它适用于除 gridlayoutmanager 之外的每个布局管理器。我在 issuetracker 上创建了一个issue。您可以为该问题加注星标以获得快速关注。
-
@gowtham6672 我做到了。
标签: android kotlin android-recyclerview android-paging android-paging-3