3

Here is the deal: I have a GridView with android:numColumns="2". The items in the GridView are ImageViews with android:layout_weight="1", so they are half the screen width. The problem is the heightproperty, it should be equal to the width. I tried to play with scaleype, so far without success. How can I set the width of the GridView elements to fill half the screen and set their height to be equal to their width?

keybee
  • 1,498
  • 20
  • 32
  • did you find the answer? – gaurang Apr 25 '17 at 10:12
  • If I remember right I showed square shaped images in the grid view, so setting their height and width to wrap_content was enough. Otherwise you can have a look at this: http://stackoverflow.com/questions/6557516/making-gridview-items-square – keybee Apr 25 '17 at 15:03

2 Answers2

2

You have to get the ImageViews width programmatically and then set the height.

But if you just use img.getWidth(); eg. in OnCreate(), it will return 0 because it hasn't been drawn yet.

So you have to do something like this in OnCreate():

ImageView img = (ImageView) findViewById(R.id.img); 
ViewTreeObserver vto = img.getViewTreeObserver();
         vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
             public boolean onPreDraw() {
                 int x;
                 img.getViewTreeObserver().removeOnPreDrawListener(this);
                 x = img.getMeasuredWidth();
                 img.setLayoutParams(new LinearLayout.LayoutParams(x,x));
                 return true;
             }
         });

This will get your Imageview's width after its been drawn and set its height equal to it.

user3666197
  • 1
  • 6
  • 50
  • 92
0

To set your ImageView equal to half the screen, you need to add the following to your XML for the ImageView:

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:scaleType="fitXY"
    android:adjustViewBounds="true"/>

To then set the height equal to this width, you need to do it in code. In the getView method of your GridView adapter, set the ImageView height equal to its measured width:

int measuredImageWidth = mImageView.getMeasuredWidth();
mImageView.getLayoutParams().height = measuredImageWidth;

Hope this helps!

Matt Logan
  • 5,886
  • 5
  • 31
  • 48