0

I have a LinearLayout in xml file and i created an ImageView in the java code. I had to create ImageView in java code instead of xml because I need to alternate an ImageView with a TextView in the same LinearLayout.

This is my LinearLayout in my xml file:

<LinearLayout
        android:id="@+id/linearLay"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="5"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:orientation="vertical">

And this is part of my java code:

public class MainActivity extends AppCompatActivity {    

        public ImageView questionImage;

           @Override
           protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.activity_main);

               LinearLayout ll = (LinearLayout)findViewById(R.id.linearLay);
               questionImage = new ImageView(this);
               LinearLayout.LayoutParams layoutParams = new 
                       LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 
                       LinearLayout.LayoutParams.MATCH_PARENT);
               layoutParams.gravity = Gravity.CENTER;
               questionImage.setLayoutParams(layoutParams);
               ((LinearLayout) ll).addView(questionImage);

               // imageview.setScaleType doesn't work
               questionImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
               questionImage.setBackgroundResource(R.drawable.imageA);
          }
}

The result is that i can see the imageA fit in all my LyinearLayout but without keeping its aspect ratio. The LinearLayout has been set with a MATCH_PARENT width and a height of 0dp due to its weight of 5 (i have others TextViews and Buttons displayed in the same activity).

What i would like to do is to display imageA in the center of my LinearLayout keeping its aspect ratio at maximum possible size(e.g. imageA = 250p x 250p, LinearLayout = 400p x 600p -> imageA resize to 400p x 400p and centered in the middle; e.g imageA = 250p x 250p, LinearLayout = 100p x 180p -> imageA resize to 100p x 100p and centered in the middle).

Why setScaleType doesn't work? Sholud i do in a different way? Could you please help me with some example?

Thanks in advance.

EDIT:

I resolved it by using questionImage.setImageResource(R.drawable.imageA);

Ramal
  • 23
  • 5

2 Answers2

1

If you want to keep the aspect ratio of your image, SET adjustViewBounds property to true of your ImageView.

1

You can set the property adjustViewBounds of the ImageView to true. Also, make sure that you set it as an src and not as background because setting it as background will make it scale and distort it.

setAdjustViewBounds
And in case of setting the src programmatically, you can use setImageDrawable

Shankha057
  • 1,296
  • 1
  • 20
  • 38