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

Asked

Viewed 58 times

2

I have a View in which I am programmatically defining its somersault 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 makes for each device, my View have different sizes defining this way: height = 50.

How do I make mine View has a size proportional to my resolution?

2 answers

2


The problem is that height and width of Layoutparams, when set via java, are values in pixels.

In order for the dimensions to remain consistent between 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);
}

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.