How to set the height of an item row in GridLayout

2019-03-11 05:51发布

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

7条回答
▲ chillily
2楼-- · 2019-03-11 06:36

This is my code for adjusting height of recycle view element based on actual aspect-ration required.

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.adapter_offers, parent, false);

    int width =  parent.getMeasuredWidth();
    float height = (float) width / Config.ASPECT_RATIO;//(Width/Height)
    RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) itemView.getLayoutParams();
    params.height = Math.round(height);
    itemView.setLayoutParams(params);
    return new MyViewHolder(itemView);
}
查看更多
登录 后发表回答