gpt4 book ai didi

android - 以编程方式为 RecyclerView 设置顶部填充不起作用?

转载 作者:行者123 更新时间:2023-11-30 00:26:49 24 4
gpt4 key购买 nike

我有 RecyclerView,它将一些项目显示为屏幕上的列表。布局如下:

 <RelativeLayout
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/top_layout">

<RelativeLayout
android:id="@+id/top_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true">

<TextView
android:id="@+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:layout_alignParentTop="true"
android:background="@android:color/holo_blue_light" />

<TextView
android:id="@+id/tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/tv1"
android:inputType="textMultiLine"
android:background="@android:color/holo_blue_light" />
</RelativeLayout>


<android.support.v7.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:clipToPadding="false"
android:scrollbars="vertical" />

</RelativeLayout>

在上面的布局中 tv1 & tv2 有一些信息要显示,它可能是单行或多行,因此给它们一个固定的高度是不可能的,因此沿着tv1tv2 的父级 -> top_view 都将高度作为包装内容。

我想要 top_view 高度的顶部填充。我正在以编程方式执行以下操作:

top_view = (RelativeLayout) findViewById(R.id.top_view );
list = (RecyclerView) findViewById(R.id.list);
list.setPadding(list.getPaddingLeft(),
top_view.getHeight(),
list.getPaddingRight(),
list.getPaddingBottom());

但是上面的代码没有效果,如果我给 RecyclerView 硬编码顶部填充 android:paddingTop="100dp" 它可以工作,但我不能给硬编码值,因为它依赖于 top_view

list 放在 top_view 下的另一件事对我不起作用,因为我对此填充有一些其他要求。

那么为什么这个以编程方式设置的 topPadding 不起作用?

最佳答案

RecyclerView 中操作 View 的方式(除了适配器)是通过 ItemDecoration

因为你想添加一个 topPadding 到你的列表它应该只影响第一个项目,所以创建你的自定义 RecyclerView.ItemDecoration 像这样:

public class PaddingTopItemDecoration extends RecyclerView.ItemDecoration {
private final int size;

public PaddingTopItemDecoration(int size) {
this.size = size;
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
if (parent.getChildAdapterPosition(view) == 0) {
outRect.top += size;
}
}
}

然后只需将它添加到您的RecylerView:

// Insert your own top padding value
list.addItemDecoration(new PaddingTopItemDecoration(value));

关于android - 以编程方式为 RecyclerView 设置顶部填充不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45208003/

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