在“FragmentStateAdapter"中覆盖“containsItem"和“getItemId"的目的是什么? [英] What is purpose of overriding `containsItem` and `getItemId` in `FragmentStateAdapter`?
问题描述
在FragmentStateAdapter
中覆盖containsItem
和getItemId
的目的是什么?
What is purpose of overriding containsItem
and getItemId
in FragmentStateAdapter
?
如果将新列表传递给 FragmentStatePagerAdapter
实现并调用 notifyDataSetChanged
,是否需要这些覆盖?
Are these overrides required if one is passing in new lists to the FragmentStatePagerAdapter
implementation and calling notifyDataSetChanged
?
从文档中可以看出,如果基础数据集正在发生变化,则两个覆盖都是必需的,并且您需要调用 notifyDataSetChanged
?
From the doc, appears both overrides are require if the underlying data set is changing, and you need to call notifyDataSetChanged
?
/**
* Default implementation works for collections that don't add, move, remove items.
* <p>
* TODO(b/122670460): add lint rule
* When overriding, also override {@link #getItemId(int)}
*/
public boolean containsItem(long itemId) {
return itemId >= 0 && itemId < getItemCount();
}
/**
* Default implementation works for collections that don't add, move, remove items.
* <p>
* TODO(b/122670460): add lint rule
* When overriding, also override {@link #containsItem(long)}.
* <p>
* If the item is not a part of the collection, return {@link RecyclerView#NO_ID}.
*
* @param position Adapter position
* @return stable item id {@link RecyclerView.Adapter#hasStableIds()}
*/
@Override
public long getItemId(int position) {
return position;
}
例如,这是我的实现
class MyAdapter(host : Fragment) : FragmentStateAdapter(host) {
data class FragItem(val newInstance : () -> Fragment, val fragId : Long)
private var fragments = mapOf<Integer,FragItem>()
override fun createFragment(position: Int): Fragment {
return fragments[position]?.newInstance?.invoke() ?: DefaultFragment()
}
fun applyDataSet(newFragments : Map<Integer, FragItem>) {
fragments = newFragments
notifyDataSetChanged()
}
override fun getItemCount() = fragments.size
override fun containsItem(itemId: Long): Boolean{
return fragments.any { it.value.fragId == itemId }
}
override fun getItemId(position: Int) : Long{
return fragments.values.elementAt(position).fragId
}
}
现在我可以去掉 getItemId
和 containsItem
吗?还是离开他们?getItemCount
怎么样?
Now can I get rid of getItemId
and containsItem
? Or leave them? What about getItemCount
?
推荐答案
getItemCount
将指示回收者要渲染多少项.当前索引将作为position
传递给createFragment
,所以很明显你需要它getItemId
和containsItem
如果您想为回收商提供稳定的 ID,则实施.拥有稳定的 ID 允许进行某些优化,通常是当它涉及对列表中不相邻的元素进行操作时.getItemCount
will instruct the recycler how many items are to be rendered. the current index will be passed asposition
tocreateFragment
, so clearly you need it- the
getItemId
andcontainsItem
implemented if you want to provide stable ID's for your recycler. having stable ID's allows for a certain optimisations to be made, usually when it involves operations on elements that are not next to each-other in the list.
这篇关于在“FragmentStateAdapter"中覆盖“containsItem"和“getItemId"的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!