Skip to content Skip to sidebar Skip to footer

How To Set Relativelayout Height Equal To Its Width?

I searched a lot to find out how its gonna work and I got nothing. I found some java code to do it dynamically but didn't work ant of theme and when opening the program, show a for

Solution 1:

The simplest solution, imo, is to subclass RelativeLayout, and override onMeasure, providing to the super the same size for width and height. For instance

@OverrideprotectedvoidonMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}

as pointed out by @ZakTaccardi, declare it in your layout like

<com.example.subclassrelativelayout 
android:layout_width="match_parent"android:layout_height="wrap_content" />

Solution 2:

Finally I myself found out what to do in this situation. so i'm gonna explain how to solve for those who have or will have my problem. in my xml ui file I set layout_weight=1 for a pair of relative layout that were in a linear layout to be splitted in the screen and actually width of each of them be the half of my screen width. my problem was about height and i tried many java codes to set relative layout height equals to its width. finally i calculated the screen width in "DP" Term and set every relative layout's height to this. this is the solved code:

Displaydisplay= getWindowManager().getDefaultDisplay();
    DisplayMetricsoutMetrics=newDisplayMetrics ();
    display.getMetrics(outMetrics);

    floatdensity= getResources().getDisplayMetrics().density;        
    floatdpWidth= outMetrics.widthPixels / density;

    RelativeLayoutRl1= (RelativeLayout) findViewById(R.id.rlv1);
    Rl1.getLayoutParams().height = (int) (dpWidth);

    RelativeLayoutRl2= (RelativeLayout) findViewById(R.id.rlv2);
    Rl2.getLayoutParams().height = (int) (dpWidth);

so i got a pure square! Enjoy it. Thanks

Post a Comment for "How To Set Relativelayout Height Equal To Its Width?"