Lahiru Chandima
Lahiru Chandima

Reputation: 24068

Android grid view item aspect ratio (make height little bit higher than the width)

I wanted to make items of my grid view perfect squares. I used the method suggested by this answer and it worked well.

Following is the code (Overridden onMeasure method of grid view item)

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}

Now I want to make the height of the items 1.2 times bigger than the item width. So, I modified the code like below.

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, (int) (widthMeasureSpec * 1.2));
}

But, the items become very long and can't even fit into the screen anymore.

Surprisingly, if I set the heightMeasureSpec to a lesser value than widthMeasureSpec, still the item height gets larger than the width. Following code makes items taller.

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, (int) (widthMeasureSpec * 0.5));
}

Can someone explain this behavior? Is there any way I can achieve what I want?

Upvotes: 1

Views: 460

Answers (2)

Raymond
Raymond

Reputation: 2372

You should not increment the MeasureSpecs but first get the size from it and then increment it. You should also call setMeasuredDimension(width, height); instead of super.onMeasure(int widthMeasureSpec, int heightMeasureSpec);. Since you are now deciding what the width and height should be.

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = (int) (MeasureSpec.getSize(widthMeasureSpec) * 1.2);
    setMeasuredDimension(width, height);
}

Upvotes: 1

Andrew
Andrew

Reputation: 1413

I didn't face behaviour that you described but usually I use next onMeasure

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int originalWidth = MeasureSpec.getSize(widthMeasureSpec);
    super.onMeasure(
            widthMeasureSpec,
            MeasureSpec.makeMeasureSpec((int) (originalWidth * 1.1f), MeasureSpec.EXACTLY)
    );
}

Upvotes: 2

Related Questions