How to set the height of an item row in GridLayoutManager

Kunal picture Kunal · Feb 5, 2016 · Viewed 66.1k times · Source

Current View is

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>

I want to display something like this Which 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?

And this is my GridLayoutManager

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

Answer

thetonrifles picture thetonrifles · Feb 6, 2016

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);        
}

Hope this could help.