0

I have a layout in xml with attributes height:700dp and width:300 dp. How I can change size this layout in code? I try something like this but I got NullPointer:

setContentView(R.layout.log_in_dialog_view);
view = findViewById(R.layout.log_in_dialog_view);
lp = view.getLayoutParams();
lp.height = 200;
lp.width = 200;
view.setLayoutParams(lp);
Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
user1302569
  • 7,131
  • 13
  • 46
  • 66

4 Answers4

0

Once you have a reference to the view, you can do this:

ViewGroup.LayoutParameters lp = view.getLayoutParameters();
lp.height = . . .;
lp.width = . . .;
view.setLayoutParameters(lp);

The values need to be in pixels. There are several threads that describe how to convert dp to pixels. Here's a code fragment from this answer to another question:

public static float convertDpToPixel(float dp,Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi/160f);
    return px;
}

You should then add 0.5f before casting to an int and assigning to one of the fields of lp.

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0
layout.setLayoutParams(new LinearLayout.LayoutParams(400,400));

after getting reference from the statement , use above sentence for setting width anbd height dynamically. If you are using linear layout in xml then use LinearLayout.LayoutParams. others wise if it is different one , then use that layout params . first one is width and second one is height in the statement . if any doubts just commment here.

Thirupathig
  • 166
  • 9
0

You can try below code

DisplayMetrics metrics = getResources().getDisplayMetrics();
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams((int) (metrics.density * 100 + 0.5f), (int) (metrics.density * 150 + 0.5f));
lp.setMargins(5, 5, 0, 0);

final ImageView imgRss = new ImageView(getApplicationContext());
imgRss.setLayoutParams(lp);
Dipak Keshariya
  • 22,193
  • 18
  • 76
  • 128
Nirali
  • 13,571
  • 6
  • 40
  • 53
0

I use WindowManager:

    DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);

height = dm.heightPixels;
width = dm.widthPixels;
    WindowManager.LayoutParams WMLP = getWindow()
            .getAttributes();
    WMLP.width = width-200;
    WMLP.height = height-200;
user1302569
  • 7,131
  • 13
  • 46
  • 66