【问题标题】:How to add margins to a RecyclerView for the last element?如何为最后一个元素为 RecyclerView 添加边距?
【发布时间】:2016-08-28 23:05:16
【问题描述】:

我有几个使用RecyclerView 的屏幕,并且在RecyclerView 之上还有一个小的Fragment。当显示Fragment 时,我想确保我可以滚动到RecyclerView 的底部。 Fragment 并不总是显示。如果我在RecyclerView 上使用了边距,我需要在显示Fragment 时动态删除和添加它们。我可以在列表的最后一项上添加边距,但这也很复杂,如果我稍后加载更多内容(即分页),我将不得不再次剥离这些边距。

如何动态添加或删除视图的边距?还有什么其他方法可以解决这个问题?

【问题讨论】:

    标签: android android-fragments layout android-recyclerview


    【解决方案1】:

    因此,如果您想在 RecyclerView 的底部添加一些填充,您可以将 paddingBottom 设置为 false,然后将 clipToPadding 设置为 false。这是一个例子

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingBottom="100dp" />
    

    【讨论】:

    • 这更容易实现,而且似乎有效。谢谢你。
    【解决方案2】:

    您应该使用Item Decorator

    public class MyItemDecoration extends RecyclerView.ItemDecoration {
    
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            // only for the last one
            if (parent.getChildAdapterPosition(view) == parent.getAdapter().getItemCount() - 1) {
                outRect.top = /* set your margin here */;
            }
        }
    }
    

    【讨论】:

    • 这似乎也可以工作,这是一个很好的建议。谢谢。
    【解决方案3】:

    我在 kotlin 中使用它来为 RecyclerView 的最后一个索引提供边距

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder(view), position: Int) {
        if (position == itemsList.lastIndex){
            val params = holder.itemView.layoutParams as FrameLayout.LayoutParams
            params.bottomMargin = 100
            holder.itemView.layoutParams = params
        }else{
            val params = holder.itemView.layoutParams as RecyclerView.LayoutParams
            params.bottomMargin = 0
            holder.itemView.layoutParams = params
        }
      //other codes ...
    }
    

    【讨论】:

    • @Redesh 在我的情况下,它会导致 java.lang.ClassCastException: androidx.recyclerview.widget.RecyclerView$LayoutParams 不能转换为 android.widget.LinearLayout$LayoutParams 不幸的是:(
    猜你喜欢
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 2016-07-19
    • 2015-09-22
    • 2019-08-19
    • 2015-09-01
    • 2018-07-20
    • 1970-01-01
    相关资源
    最近更新 更多