在运行时获取RecyclerView子视图的高度

时间:2015-06-08 14:05:08

标签: android runtime android-recyclerview

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

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

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

编辑:我已尝试过onLayoutChildren,因为yigit建议

@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

2 个答案:

答案 0 :(得分:5)

LinearLayout.LayoutParams - 根据您的主要布局,这可能是RelativeLayout.LayoutParams mParentContainer - 这是RecyclerView - 传递给你的适配器 Utils.dpToPx(8 + 15); - 这里增加了利润,因为它们不计入衡量标准 totalHeight + = 1; - 是使适配器绑定下一个视图持有者;)

在View Holder中:

"oLanguage": {
    "oAria": {
        "sSortAscending": ": activate to sort column ascending",
        "sSortDescending": ": activate to sort column descending"
    },
    "oPaginate": {
        "sFirst": "First",
        "sLast": "Last",
        "sNext": "Next",
        "sPrevious": "Previous"
    },
    "sEmptyTable": "No data available in table",
    "sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",
    "sInfoEmpty": "Showing 0 to 0 of 0 entries",
    "sInfoFiltered": "(filtered from _MAX_ total entries)",
    "sInfoPostFix": "",
    "sDecimal": "",
    "sThousands": ",",
    "sLengthMenu": "Show _MENU_ entries",
    "sLoadingRecords": "Loading...",
    "sProcessing": "Processing...",
    "sSearch": "Search:",
    "sSearchPlaceholder": "",
    "sUrl": "",
    "sZeroRecords": "No matching records found"
 }

答案 1 :(得分:0)

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

如果它调整视图大小,请在onBind中执行此操作并自行测量文本视图以决定是否要启用该按钮。