Adarsh Adarsh - 2 months ago 17
Android Question

Setting LinearLayout in different screen size

I have a

LinearLayout
which is made programmatically like this:

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


80 is my
listLinear
width. I want my
LinearLayout
width to be 80. My
LinearLayout
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

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,
    ViewGroup.LayoutParams.MATCH_PARENT);

listLinear.setLayoutParams(listParam);