【问题标题】:Get height for RecyclerView child views at runtime在运行时获取 RecyclerView 子视图的高度
【发布时间】:2020-12-31 05:10:40
【问题描述】:

我正在尝试制作一个可展开的 TextView,当用户按下按钮时它会展开/折叠。 TextView 和 ImageButton 在 CardView 中,添加到 RecyclerView 中。

展开/折叠效果很好,但现在我只想在 TextView 高度超过某个最大高度时添加 ImageButton。但是当我在 LayoutManager 的 addView 方法中计算高度时,它返回 0,可能是因为 TextView 还没有任何文本。

是否有任何我可以覆盖的回调方法在 CardView 获取它的新内容后触发,以便我可以评估 TextView 的高度?

编辑:我已经按照 yigit 的建议尝试了 onLayoutChildren

@Override
public void onLayoutChildren (RecyclerView.Recycler recycler, RecyclerView.State state) {
    super.onLayoutChildren(recycler, state);
    Log.d("LayoutManager","State Count: " + state.getItemCount());

    for (int i = 1; i < state.getItemCount(); i++) {
        View v = recycler.getViewForPosition(i);
        TextView ct = (TextView) v.findViewById(R.id.comment_text);
        Log.d("LayoutManager", "Comment height: " + ct.getMeasuredHeight());
    }
}

结果输出:

D/LayoutManager﹕ State Count: 4
D/LayoutManager﹕ Comment height: 0
D/LayoutManager﹕ Comment height: 0
D/LayoutManager﹕ Comment height: 0

【问题讨论】:

    标签: android runtime android-recyclerview


    【解决方案1】:

    LinearLayout.LayoutParams - 根据您的主要布局,这可能是RelativeLayout.LayoutParams

    mParentContainer - 这是RecyclerView - 传递给你的适配器

    Utils.dpToPx(8+15); - 此处添加边距导致它们不计入度量

    totalHeight += 1; - 是让适配器绑定下一个视图持有者

    在 ViewHolder 中:

    int totalHeight = 0;
    for (int i = 0; i < getItemCount(); i++){
    
        View chView = viewHolder . itemView;
        chView.measure(
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        );
    
        totalHeight += chView.getMeasuredHeight();
        totalHeight += Utils.dpToPx(8 + 15);
    }
    
    totalHeight += 1;
    LinearLayout.LayoutParams listParams = (LinearLayout.LayoutParams) mParentContainer . getLayoutParams ();
    listParams.height = totalHeight;
    mParentContainer.setLayoutParams(listParams);
    
    

    【讨论】:

    • 这种方法返回接近 的实际高度,但与我在 Photoshop 中从屏幕截图中测量的实际值相差几个像素。我最好在布局管理器中覆盖 onLayoutCompleted,使用 myRecyclerView.findViewHolderForAdapterPosition(0) 获取 viewHolder,然后使用 holder.itemView.getHeight()。
    【解决方案2】:

    您可以在 LayoutManager 中覆盖 onLayoutChildren 并在 state.isPreLayout 返回 false 时对其进行测量。我希望您不会更改视图的总大小,因为 LayoutManager 不会看到此更改。此外,由于布局请求在该阶段被禁用,您的视图将不会获得新的度量和布局。

    如果它调整了您的视图大小,请在 onBind 中执行并自己测量 textview 以确定您是否要启用按钮。

    【讨论】:

    • 感谢您的回复,但这也没有帮助,仍然得到 height = 0
    • 它确实有效,你错过了!state.isPreLayout 检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多