CoXier CoXier - 3 months ago 14
Android Question

RecyclerView implement GridView

Problem



I want to use
RecyclerView
to implement
GridView
.In fact I need to display all local photos in
RecyclerView
which has 3 columns.I know about
GridLayoutManager


My code :

mManager = new GridLayoutManager(this,3);


And the item
XML
:

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />


however how can I set the item view (
ImageView
)'s width and height?

Solution



I define a custom view:

public class RatioImageView extends ImageView {

private int originalWidth;
private int originalHeight;


public RatioImageView(Context context) {
super(context);
}


public RatioImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}


public RatioImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}


public void setOriginalSize(int originalWidth, int originalHeight) {
this.originalWidth = originalWidth;
this.originalHeight = originalHeight;
}


@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (originalWidth > 0 && originalHeight > 0) {
float ratio = (float) originalWidth / (float) originalHeight;

int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);


if (width > 0) {
height = (int) ((float) width / ratio);
}

setMeasuredDimension(width, height);
}
else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}


Is there another solution?


Answer

Instead of creating Custom ImageView when you are creating your view inside onCreateViewHolder() method by inflating your recycler item view, you can set width and height to your ImageView using layoutParamas.

If you want 3 columns then you can get screen width and divide it into 3 and pass that to your RecyclerView Adapter and use it in onCreateViewHolder() to apply.