CoXier CoXier - 1 year ago 99
Android Question

RecyclerView implement GridView


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

My code :

mManager = new GridLayoutManager(this,3);

And the item

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android=""
android:layout_height="wrap_content" />

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


I define a custom view:

public class RatioImageView extends ImageView {

private int originalWidth;
private int originalHeight;

public RatioImageView(Context 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download