1

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?

Community
  • 1
  • 1
Lahiru Chandima
  • 22,324
  • 22
  • 103
  • 179

2 Answers2

2

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)
    );
}
Andrew
  • 1,383
  • 7
  • 21
1

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);
}
Raymond
  • 2,276
  • 2
  • 20
  • 34
  • Forgot to mention to call `setMeasuredDimension(width, height);` now instead of `super.OnMeasure`. Since you now decide yourself what the width and height should be. – Raymond Apr 25 '17 at 12:20
  • `setMeasuredDimension()` did make the necessary size adjustment, but now I can't see the content of the item. I can see the outline of the item when I clicked on it since item is clickable. Anyway, Andrew's method worked for me. – Lahiru Chandima Apr 25 '17 at 12:26