【问题标题】:How to get height/width of a RecyclerView cell in onBindViewHolder?如何在 onBindViewHolder 中获取 RecyclerView 单元格的高度/宽度?
【发布时间】:2021-02-14 06:14:06
【问题描述】:

我已经看到了这个问题的其他答案,但没有一个对我有用;例如这里的最佳答案 (How to get the height of recyclerview item in "onBindViewHolder") 说要这样做:

view.measure(
             View.MeasureSpec.makeMeasureSpec(recyclerViewWidth, View.MeasureSpec.EXACTLY),
             View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

但随后执行view.getMeasuredHeight() 只会返回我为recyclerViewWidth 传递的任何内容。

基本上,我想将回收器视图单元格中组件的大小设置为单元格大小的分数,但这些分数取决于单元格的位置。我有点沮丧,因为这在 iOS 中很简单,而在 android 中似乎更复杂。

【问题讨论】:

    标签: android android-layout android-recyclerview


    【解决方案1】:

    我不喜欢在 Android 上通过代码设置百分比。如果您确实想设置视图相对于其父视图的大小,ContraintLayout 是您根据百分比准则设置项目的最佳朋友,障碍和比率是您应该研究的东西,它很有效,您不必担心自己计算。

    https://developer.android.com/reference/androidx/constraintlayout/widget/ConstraintLayout

    【讨论】:

    • 问题是百分比取决于单元格的位置,因此在 XML 文件中硬编码不允许我稍后更改/设置百分比。
    • 你可以尝试通过代码设置约束,具体取决于索引。
    猜你喜欢
    • 2016-12-10
    • 2015-12-16
    • 2012-11-23
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2019-12-29
    相关资源
    最近更新 更多