Saturday, 8 December 2018

How to programmatically set the width of the LinearLayout or ImageView or RelativeLayout?


First of all get the device screen width:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
try {
    display.getRealSize(size);
} catch (NoSuchMethodError err) {
    display.getSize(size);
}
int width = size.x;
int height = size.y;
now just create a LayoutParams and set it to the Text:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams((int)(width/3),
                    LinearLayout.LayoutParams.WRAP_CONTENT);  

mMainLinearLayout.setLayoutParams(lp);
// OR
mProfileImage.setLayoutParams(lp);
//OR

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams((int)(width/3),
                    LinearLayout.LayoutParams.WRAP_CONTENT);  

mLoginRelativeLayout.setLayoutParams(lp);

as same for all other layouts
which is provide according to screen size of device .