Adarsh Adarsh - 1 year ago 83
Android Question

Setting LinearLayout in different screen size

I have a

which is made programmatically like this:

listLinear=new LinearLayout(this);
LinearLayout.LayoutParams listParam = new LinearLayout.LayoutParams(80,

80 is my
width. I want my
width to be 80. My
looks perfectly as I want in 4.5 inch screen but when I test it in 5 inch display it just shrinks and looks small in size.

Why is it happening?

Answer Source

The problem is the constructor of LinearLayout.LayoutParams expects the width/height in pixels.

For your layout to look the same on all screen sizes, you should define its width in dip (density-independent pixels).

Something like this should work:

listLinear = new LinearLayout(this);

int widthDp = 50; // desired width in dp, adjust this as you'd like

// converting dp to pixels
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int widthPx = Math.round(
    widthDp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));

LinearLayout.LayoutParams listParam = new LinearLayout.LayoutParams(widthPx,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download