我目前的问题是,我的 LoadStateAdapter
显示加载和错误状态,但它没有居中在我的 recyclerview
中,而 recyclerview
使用的是 gridlayout 作为 layoutmanager。我在官方的 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() }
}
}
}
Layout.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
有关,您可以查看https://stackoverflow.com/questions/63509661/how-to-prepare-setspansizelookup-in-gridlayoutmanager/63511928#63511928。 - Mohammed AlaaLoadStateAdapter
总是在我的recylerview中的最后一项,所以我必须将我的最后一项的跨度大小设置为与其他项不同,对吧?但问题在于,有时候LoadStateAdapter
并没有显示出来,因为没有错误或加载状态等。 - Andrew