0

I know this question has been asked many times before, but all the answers aren't helping me or seem to contradict each other.

  • This one suggests I need to programmatically set the width of the ImageView.
  • This one and this one suggest doing it by overriding the onMeasure() method on ImageView in a subclass.
  • This one suggests it can be done with just a quick code snippet:

.

ImageView imageView=new ImageView(context);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(bitmap);
imageView.setMaxHeight(maxHeight);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
layout.addView(imageView);

Thought I've tried this (I'm new to Android, sorry) and it didn't seem to work for me. My goal is to programmatically construct the following:

<horizontal layout>
    <container width_weight=X>
        <image A fills parent width/>
    </container>
    <container width_weight=Y>
        <image B fills parent width/>
    </container>
    <container width_weight=Z>
        <image C fills parent width/>
    </container>
</horizontal layout>

where X, Y, and Z are different positive integers. Can someone please help me make sense of all this information?

Community
  • 1
  • 1
Robert Martin
  • 16,759
  • 15
  • 61
  • 87
  • I don't want to write an XML layout -- I want to do it programatically. – Robert Martin Feb 23 '15 at 17:30
  • Why don't you want to write an XML layout? You'll be writing and maintaining at least 5x as much code to do the same thing, not to mention not being able to use any of the tools to [provide alternate resources](http://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources). – ianhanniballake Feb 23 '15 at 17:35

1 Answers1

1

Set the width and height via the LayoutParams for your ImageView:

ImageView imageView = new ImageView(this);
int mp = LinearLayout.LayoutParams.MATCH_PARENT;
imageView.setLayoutParams(new LinearLayout.LayoutParams(mp, mp));
layout.addView(imageView);

This is considering that your container is a LinearLayout.

Simas
  • 43,548
  • 10
  • 88
  • 116
  • Hrm... This doesn't work. It causes Image A to take up the whole screen (rather than respecting the weight=X) and worse, it doesn't actually stretch the image width-wise -- instead it already fits height-wise so it stops stretching. I can no longer see image B or C. – Robert Martin Feb 23 '15 at 17:38
  • @RobertMartin I think you should post your layout instead of layouts with obscure attributes like horizontal layout and width_weight. – Simas Feb 23 '15 at 17:40