Calling getWidth of parent in onCreateViewHolder

☆樱花仙子☆ 提交于 2019-12-12 03:28:26

问题


Is it ok to get parent's width in onCreateViewHolder at RecyclerView adapter? Are parent's dimensions measured at that state so I don't get 0 when I call getWidth() on parent?


回答1:


Yes, the parent is actually the RecyclerView. It has both a non-zero getWidth() and getMeasuredWidth() by the time onCreateViewHolder is called.

Easy way to verify this is set your debugger to stop in the method and inspect the parent.

parent = android.support.v7.widget.RecyclerView{d08d560 VFED..... ......ID 0,0-1080,1698 #7f0c0074 app:id/recyclerView1}

mMeasuredWidth = 1080
mLeft = 0
mRight = 1080



回答2:


I came across a case where I actually got 0 on some occasions when calling parent.getWidth(), so I had to use getMeasuredWidth(). For anybody facing this issue or wondering about it, I suggest you read this answer



来源:https://stackoverflow.com/questions/39000258/calling-getwidth-of-parent-in-oncreateviewholder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!