1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > item不可见 recycleview_RecyclerView不显示Item

item不可见 recycleview_RecyclerView不显示Item

时间:2024-08-06 15:13:46

相关推荐

item不可见 recycleview_RecyclerView不显示Item

今天在写一个横向的RecyclerView,写完运行后怎么都没显示item内容,开始以为是数据没加载,打断点调试后发现数据加载是没问题的,瞬间懵逼。。。

Tools -> Layout Inspector 看下布局结构,能看到item存在,但是检查属性发现所有item的宽度都为0,所以在界面上看不到有item显示,可是item是有固定宽度的。。。

到这,其实可以基本定位到item的布局加载问题,而我使用的加载的方式是:

View.inflate(parent.context, R.layout.item_home_channel_normal, null)

后面修改后,正确的加载方式是:

LayoutInflater.from(parent.context).inflate(R.layout.item_home_channel_normal, parent, false)

查看源码会发现View.inflate()内部就是使用LayoutInflater的inflate()方法

inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)

关键在于三个参数的使用:

如果inflate(layoutId, root, false ) 则layoutId的最外层的控件的宽高是没有效果的

如果inflate(layoutId, root, true ) 则layoutId的最外层控件的宽高能正常显示

郭大神的结论是:

1、如果root为null,attachToRoot将失去作用,设置任何值都没有意义。

2、如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。

3、如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。

4、在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。

上面的View.inflate(parent.context, R.layout.item_home_channel_normal, null)相当于

inflate(layoutId, null, false),所以显示没有达到预期。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。