gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:35:06 24 4
gpt4 key购买 nike

我正在尝试制作一个可展开的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com