Android Java set the height to a fraction of width

623 views Asked by At

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.

2

There are 2 answers

0
Anusha Harish On

You can use DisplayMetrics like below

DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        height = metrics.heightPixels;
        width = metrics.widthPixels;
       int homePageButtonPanelHeight = height / 7;

       LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
            homePageButtonPanelHeight - 5, homePageButtonPanelHeight - 5);
       LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(
            homePageButtonPanelHeight, homePageButtonPanelHeight + 30);

      RelativeLayout.LayoutParams paramIcon = new RelativeLayout.LayoutParams(
            homePageButtonPanelHeight - 5, homePageButtonPanelHeight - 5);


      icon.setLayoutParams(paramIcon);

      btn1.setLayoutParams(params2);

      btn2.setLayoutParams(params2);
1
Prabhuraj On

Try this

imageView.setLayoutParams(new LayoutParams(width, width/3));