Android: How can I set my custom surfaceview to a fixed size ratio in xml?

android, surfaceview

Solution

In the onCreate method of your activity you could read the resolution of the screen and set the layout width and height to it.

Example assuming you're using RealtiveLayout:

private void create43RatioSurface() {
    SurfaceView surfaceView43 = (SurfaceView)findViewById(R.id.surfaceView1);

    DisplayMetrics metrics = getResources().getDisplayMetrics();
    int height = 0;
    int width = 0;

    if(metrics.widthPixels < metrics.heightPixels){
        width = metrics.widthPixels;
        height= (metrics.widthPixels/4) * 3 ;
    } else {
        height= metrics.heightPixels;
        width= (metrics.heightPixels/4) * 3 ;
    }

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, height);
    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);

    surfaceView43.setLayoutParams(layoutParams);        
}

Problem

I am trying to have a surfaceview (a custom class which extends surfaceview) that I add in the xml layout to have a fixed size ratio: 4:3 (length to width). I want it to fill as much as it can of it's parent, either on the length or width but once it reaches the full length or width it will adjust the other side to have a fixed size ratio like I said before. How can I achieve such a thing? Thanks.

Original source