gpt4 book ai didi

android - 在 RecyclerView ItemDecoration.getItemOffsets 中获取 subview 高度

转载 作者:搜寻专家 更新时间:2023-11-01 07:45:12 25 4
gpt4 key购买 nike

我正在尝试创建一个 ItemDecoration,它将通过向最后一个项目动态添加填充来保持 RecyclerView 的最小高度。

要计算填充量,我需要知道所有 child 的总高度。我通过获取单个 View 的高度并将其乘以适配器中的项目数来对此进行近似。

我遇到的问题是 view.getHeight() 并不总是返回正确的高度。通常第一次调用 getItemOffsets() 时高度比它应该的小很多(例如 30px vs 300px)。即使我在布局 XML 中为 subview 提供固定高度,也会发生这种情况。我猜这与测量/布局周期有关,因为我不确定如何在 ItemDecoration 中获得正确的 View 尺寸。

在 getItemOffsets() 中以编程方式获取 subview 高度的正确方法是什么?

元素装饰:

public class MinHeightPaddingItemDecoration extends RecyclerView.ItemDecoration {
private static final String LOG_TAG = MinHeightPaddingItemDecoration.class.getSimpleName();

private int mMinHeight;

public MinHeightPaddingItemDecoration(int minHeight) {
super();
mMinHeight = minHeight;
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView recyclerView, RecyclerView.State state) {
int itemCount = state.getItemCount();
int lastPosition = itemCount - 1;
int itemPosition = recyclerView.getChildAdapterPosition(view);
int layoutPosition = recyclerView.getChildLayoutPosition(view);

// If this view isnt on screen then do nothing
if (layoutPosition != RecyclerView.NO_POSITION && itemPosition == lastPosition) {

// NOTE: view.getHeight() doesn't always return the correct height, even if the layout is given a fixed height in the XML
int childHeight = view.getHeight();

int totalChildHeight = childHeight * itemCount;

int minHeight = getMinHeight();
if (totalChildHeight < minHeight) {
outRect.bottom = minHeight - totalChildHeight;
}
}
}

private int getMinHeight() {
return mMinHeight;
}
}

recycler_view_item.xml

<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable name="controller" type="my.ViewController"/>
</data>

<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_gravity="center"
android:clickable="true"
android:onClick="@{() -> controller.doSomething()}">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Child layout"
/>
</RelativeLayout>

</android.support.v7.widget.CardView>
</layout>

最佳答案

我找到了固定大小的 subview 的解决方法。我仍然不确定如何处理动态大小的布局。

// NOTE: view.getHeight() doesn't always return the correct height 
// NOTE: even if the layout is given a fixed height in the XML.
// NOTE: Instead directly access the LayoutParams height value
int childHeight = view.getLayoutParams().height;

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

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