本文介绍了如何在GridLayoutManager中设置项目行的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在onCreateViewHolder中膨胀的我的回收站物品

My Recycler Item which inflate in onCreateViewHolder

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="16dp">

    <ImageView
        android:id="@+id/gridListImageView"
        android:layout_width="96dp"
        android:layout_height="96dp"
        android:src="@drawable/a" />

    <TextView
        android:id="@+id/gridListView_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

我要显示类似的内容哪一排的高度是Recycler View高度的一半?并在其余空间中添加填充?我可以通过GridLayoutManager做到吗?

I want to display something like thisWhich has one row of half the height of recycler View?And add padding to the rest of the space?Can i do this by GridLayoutManager?

这是我的GridLayoutManager

And this is my GridLayoutManager

        GridLayoutManager glm = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(glm);

推荐答案

在适配器中扩展视图的布局时,可以以编程方式设置其高度.为了评估要使用的适当高度,您可以依赖父ViewGroup(即RecyclerView本身).这是一个示例:

When inflating layout for your views in adapter, you can set their height programmatically. In order to evaluate proper height to use you can rely on parent ViewGroup (that is the RecyclerView itself). Here it is a sample:

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = mLayoutInflater.inflate(R.layout.view_item, parent, false);
    // work here if you need to control height of your items
    // keep in mind that parent is RecyclerView in this case
    int height = parent.getMeasuredHeight() / 4;
    itemView.setMinimumHeight(height);
    return new ItemViewHolder(itemView);        
}

希望这会有所帮助.

这篇关于如何在GridLayoutManager中设置项目行的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 04:48