Developing an app in Android Studio
I have the width of my ImageView
set to "match_parent".
I am trying to set the height of it to "the width / 3". In other words I am trying to maintain an aspect ratio of 3:1 regardless of the screen size of the device it runs on.
I know I can't do it in XML because you can only set values to literal values.
At runtime I can use this statement.
img.getLayoutParams().height = img.getWidth() / 3;
and that will work but if I put that in the onCreate
or the onStart methods getWidth
returns 0 because the view hasn't been created yet. There's got to be a place I can place this code so that it simply runs after the Activity
starts.
I tried this:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
float RATIO = 1/3;
setLayoutParams(new RadioGroup.LayoutParams((int)RATIO * w, w));
}
But the onSizeChanged
and setLayoutParams
are turned red and I don't know where I need to put this code.
You can use
DisplayMetrics
like below