android - 在运行时获取 RecyclerView subview 的高度

标签 android runtime android-recyclerview

我正在尝试制作一个可展开的 TextView,它会在用户按下按钮时展开/折叠。 TextView 和 ImageButton 位于 CardView 中,该 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

最佳答案

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

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

Utils.dpToPx(8+15); - 这里添加边距是因为它们不计入测量值

totalHeight += 1; - 是为了让适配器绑定(bind)下一个 View 持有者

在 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);

关于android - 在运行时获取 RecyclerView subview 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30711305/

相关文章:

java - Android 将字符串保存到数据库

runtime - 在浏览器上显示 Storm 集群 bolt 的结果

java - Firebase 更新后 RecyclerView 不刷新

android - 错误夸大设计支持库中的任何内容

android - 在构造函数中设置 BitmapDrawable 资源

java - SoundCloud 官方 Java ApiWrapper,保存 token 的请求被拒绝并显示 401

java - 无法解析Xml数据到RecyclerView

c++ - 是否可以从 Objective-C 获得中间 C 代码?

algorithm - 什么更大 : O(mn) OR O((m^2)/n)?

android - 如何在 RecyclerView 适配器中高亮搜索文本