3

I am programatically adding ImageView elements into a horizontal Linear Layout. Then I set the scaleX and scaleY properties to "2" on one of the ImageView resources. The image gets scaled properly, but it doesn't move the other ImageView elements, instead of that it overlaps them. I don't like the image to overlap with other images. How can I fix that? Here's my code:

    int resources[] = {R.drawable.desert, R.drawable.koala, R.drawable.jellyfish,
                       R.drawable.lighthouse, R.drawable.desert};

    for(int i=0; i<5; i++) {
        ImageView logo = new ImageView(this);
        logo.setLayoutParams(new LinearLayout.LayoutParams(100, 75));
        logo.setImageResource(resources[i]);
        logosContainer.addView(logo);
    }

    ImageView middleImage = (ImageView) logosContainer.getChildAt(2);
    middleImage.setScaleX(middleImage.getScaleX() * 2);
    middleImage.setScaleY(middleImage.getScaleY() * 2);

The result from the code looks like this: http://imageshack.us/a/img15/2811/scaleal.jpg

You can clearly see that the scaled image overlaps with the other images.

user1718159
  • 561
  • 1
  • 6
  • 12

1 Answers1

0

Your ImageViews are already measured and placed in the container when you leave the loop. You would have to refresh your layout to make this work, which is tricky and often leads into "removing all views and adding them again". So why don't you just do the "scaling" in the loop?

for(int i=0; i<5; i++) {
   ImageView logo = new ImageView(this);
   if(i==middleImageIndex){
      logo.setLayoutParams(new LinearLayout.LayoutParams(100*2, 75*2,1));
   } else {
      logo.setLayoutParams(new LinearLayout.LayoutParams(100, 75,1));
   }
   logo.setImageResource(resources[i]);
   logosContainer.addView(logo);
}

The last parameter (100,75, 1) is the weight of the view, which makes sure that each ImageView is equally important and doesn't get overlapped.

Another note: setScale requires API level 11 or higher, which could cut a lot of users out there

Community
  • 1
  • 1
Chris
  • 4,403
  • 4
  • 42
  • 54
  • Hi Chris, thank you for your help, but I need to set the scaling after the images are placed in the container. I will add touch events on which I'll be using animations to animate the scaling of a chosen image. – user1718159 Oct 04 '12 at 10:38