java - Recyclerview布局管理器在Android中滚动后获取视图位置
问题描述
Recyclerview
是LinearLayoutManager
这样滚动的lm.scrollToPositionWithOffset(position, offset)
。如何在滚动之前获取滚动位置的视图?将滚动的视图在滚动后返回 null,因为仍未创建。我试过了Runnable
,Observer
但onLayoutCompleted
仍然为空。如何获得视野?
lm.scrollToPositionWithOffset(position, offset);
recyclerView.post(new Runnable(){
@Override
public void run(){
View v1 = recyclerView.getChildAt(position); // returning null.
View v2 = recyclerView.getLayoutManager().getChildAt(position); // returning null.
}
});
recyclerView.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
View v1 = recyclerView.getChildAt(position); // returning null.
View v2 = recyclerView.getLayoutManager().getChildAt(position); // returning null.
recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}});
@Override // in LinearLayoutManager
public void onLayoutCompleted(RecyclerView.State state) {
super.onLayoutCompleted(state);
View v1 = recyclerView.getChildAt(position); // returning null.
View v2 = this.getChildAt(position); // returning null.
}
解决方案
如果您尝试修改视图内容,您应该这样做:
修改您当前的模型:
itemList.get(position) // and change any property here to handle that state
称呼
adapter.notifyItemChanged(position)
确保您有正确的逻辑
ViewHolder
来处理此更改,并且应该修改您的View
但如果你真的想通过 改变事情,ViewHolder
你也可以这样做:recyclerView.findViewHolderForAdapterPosition(position)
然后:
if (null != holder) {
holder.itemView.findViewById(R.id.YOUR_ID) // call any method do you want to
}
我真的推荐第一个选项,但这取决于你。希望这对你有帮助!
推荐阅读
- java - java中String到arrayList的转换问题
- json - Pug.js 在每个循环中使用空格键或空格访问 json 键
- sql - 使用 SQL Server 选择除 ONE 之外的所有列
- python - 如何在 Jupyter Notebook 中获得多个 True/False 答案行?
- assembly - YASM mov 指令给出错误:操作数 1 的大小无效
- reactjs - 更新反应 useState 挂钩嵌套二维数组
- amazon-web-services - 当我更改路径时,基于 AWS ALB 目标组路径的路由不起作用
- java - 在eclipse中构建我的java应用程序后出错
- reactjs - http://localhost:5000/auth/google/callback 404 错误
- jmeter - 我可以使用 csvdataconfig 中的变量作为 jmeter 目录列表中的源目录吗