【发布时间】:2020-12-26 22:30:52
【问题描述】:
我如何才能获得我的PagingData<Product> 持有的当前数量的项目?我找到的唯一解决方案是调用 shopListAdapter.itemCount 但这总是返回 0。
我要做的是:获取我的 PagingAdapter 当前显示的项目的当前数量,将此值提交给我的 shopViewModel,然后在另一个片段(DialogFragment)中使用此值。或者:从我的视图模型中的PagingData<Product> 获取项目数量
这是我目前的方法
主片段
@AndroidEntryPoint
class ShopFragment : Fragment(R.layout.fragment_shop), ShopAdapter.OnItemClickListener {
private val shopViewModel: ShopViewModel by navGraphViewModels(R.id.nav_shop) { defaultViewModelProviderFactory }
private var _shopBinding: FragmentShopBinding? = null
private val shopBinding: FragmentShopBinding get() = _shopBinding!!
@Inject lateinit var shopListAdapter: ShopAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_shopBinding = FragmentShopBinding.inflate(inflater, container, false)
return shopBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
collectShopList()
}
private fun collectShopList(){
shopViewModel.shopPagingData.observe(viewLifecycleOwner) {
shopListAdapter.submitData(viewLifecycleOwner.lifecycle, it)
shopViewModel.setItemAmount(shopListAdapter.itemCount)
}
}
}
对话框片段
@AndroidEntryPoint
class ShopFilterFragment : DialogFragment() {
private val shopViewModel: ShopViewModel by navGraphViewModels(R.id.nav_shop) { defaultViewModelProviderFactory }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_shop_filter, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
shopViewModel.itemAmount.observe(viewLifecycleOwner) {
toast(it.toString()) <-- Always displays 0
}
}
}
视图模型
class ShopViewModel @ViewModelInject constructor(
private val shopRepository: ShopRepository
) : ViewModel() {
private val _itemAmount = MutableLiveData<Int>()
val itemAmount: LiveData<Int> get() = _itemAmount
private val query = MutableLiveData(QueryHolder(null, null, null))
val shopPagingData = query.switchMap { query -> shopRepository.search(query).cachedIn(viewModelScope) }
fun search(newQuery: QueryHolder) {
query.value = newQuery
}
fun setItemAmount(amount: Int) {
_itemAmount.value = amount
}
}
【问题讨论】:
-
“获取我的 PagingAdapter 当前显示的项目的当前数量”——该值似乎没有意义。这将是几页的数据,它可能会或可能不会类似于要从该数据所在的任何位置进行分页的数据量。如果您的意思是“获取可能项目的总数,如果用户对所有内容进行了分页”,那么在不进行所有分页的情况下是否可知这取决于数据源,而不是取决于分页 3。
-
例如,如果您的数据是由 Room 或其他东西支持的,您可以查询匹配相同条件的行数,并肯定知道有多少 Paging 将分页(除非数据更改)。但是,如果您的数据由不返回总页数或总页数的 Web 服务提供支持,那么在您翻阅所有内容并最终用完数据之前,您将无法知道可能的总页数.
-
@CommonsWare 也许我用错了词,所以让我再次尝试解释一下:假设我总共请求三页。结合起来,这将导致用户可能看到 30 种不同的项目。我的问题是:是否可以计算给定当前查询的所有页面所持有的项目数量(这里是数字 30)以将其显示给用户?我的数据不是按房间备份的,而是通过云火库备份的。
标签: android mvvm paging android-paging