lannyf
lannyf

Reputation: 11025

how to dynamically set imageView height based on its width

Having some imageViews in a list row.

The count of the imageView in the row are different, i.e. could be three or two imageView.

For the width it could be specified using

layout_width="0dp"
layout_weight="1dp" 

for every imageView in the row. But the problem is the height, it should be 90% of the width of the imageView if the row has two imageView, and 80% of the width is the row has three imageView.

Is there way to do that in xml? If not, where is the best place to do calc and set the height without too much overhead on the drawing? Thanks!

Upvotes: 0

Views: 977

Answers (2)

lannyf
lannyf

Reputation: 11025

Not sure if there is a way to do in xml. But this works in code, do it in the adapter::getView(), after get the corresponding imagView, change its height layoutParam but keep the width one.

Point size = new Point();

((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getSize(size);
int screenWidth = size.x;

int columnNumber = (isItThree ? 3 : 2);
double ratio = (isItThree ? 0.8 : 0.9)

int desiredImageHeight = screenWidth/colunmNumber * ratio;

ViewGroup.LayoutParams imglayoutParams = imgView.getLayoutParams();
imglayoutParams.height = desiredImageHeight;
imgView.setLayoutParams(imglayoutParams);

Upvotes: 1

Mohammad Arman
Mohammad Arman

Reputation: 7065

In order to maintain the ratio between height and width the best practice is: Defining one of its property with a value in dp and another with wrap content.

In your case:

android:layout_width="20dp"
android:layout_heignt="wrap_content"

By doing this the height should be adjusted according to the ratio of given width.

Upvotes: 0

Related Questions