LinearLayout dimensions, defined in java, do not maintain proportionality between resolutions

2

I have a View in which I am programmatically defining its width and width in this way:

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) linear.getLayoutParams();
params.height = 50;
params.width = 50;
linear.setLayoutParams(params); 

However I have two devices with different resolutions, and this means that for each device, my View has different sizes, thus defining: height = 50 .

How do I get my View size proportional to my resolution?

    
asked by anonymous 25.11.2016 / 01:52

2 answers

2

The problem is that height and width LayoutParams , when defined via java, are values in pixels.

For dimensions to remain consistent across different screen resolutions you should think in terms of dp and convert the values to pixel before using them.

    ......
    ......
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) linear.getLayoutParams();
    params.height = convertDpToPixels(50, this);
    params.width = convertDpToPixels(50, this);
    linear.setLayoutParams(params); 
}

public static int convertDpToPixels(float dp, Activity context){

    DisplayMetrics metrics = new DisplayMetrics();
    context.getWindowManager().getDefaultDisplay().getMetrics(metrics);
    float density = metrics.density;
    return (int) Math.ceil(dp * density);
}
    
25.11.2016 / 11:54
0

According to the Android website, you should ideally have a layout for each screen size. However, if you only do xhdpi (2x) and hdpi (1.5x), it can adjust to mdpi (1x) and ldpi (0.75x) because of proportionality. And it does less work than trying to automatically adjust for all resolutions.

    
25.11.2016 / 02:17