10

Can someone please tell me how to set the android:layout_weight and android:layout_width XML attributes in code for dynamically created views?

Reference: XML Table layout? Two EQUAL-width rows filled with equally width buttons?

Community
  • 1
  • 1
Fran Fitzpatrick
  • 17,902
  • 15
  • 33
  • 34

3 Answers3

19

Use ViewGroup.LayoutParams.

LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, 
                                   LayoutParams.WRAP_CONTENT);
myview.setLayoutParams(lp);

You can also specify fixed pixel sizes in the constructor, instead of the constants. But fixed pixels are a bad idea on android due to the variety of devices.

You can calculate the pixels from a dp size though, which is ok:

float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 
                                         10, getResources.getDisplayMetrics());

(Here: convert 10dp to a pixel value)

  • Well, I'm trying to make two equal-sized buttons. In XML, you do it like this: , but I can't figure out how to do that in Java. – Fran Fitzpatrick Sep 11 '11 at 14:41
  • 1
    I provided a similiar answer [here](http://stackoverflow.com/questions/7056072/android-how-to-place-two-relative-layouts-one-on-the-left-and-one-on-the-right/7056089#7056089). This is with two `RelativeLayout`s, but it works the same way with two `Button`s. –  Sep 11 '11 at 14:47
  • Yup, that did it! Didn't know you could add LayoutParams to .addView() like that. Thanks! – Fran Fitzpatrick Sep 11 '11 at 14:56
  • It's worth noting that a `LinearLayout` must use `LinearLayout.LayoutParams` and not the generic `ViewGroup.LayoutParams` (which compiles but then fails at run-time). This may or may not be true of other layouts but I was scratching my head over this for quite a while – Neil C. Obremski Jan 11 '21 at 22:58
4

Try

setLayoutParams(new LayoutParams(width, height))

The docs for the constructor says:

ViewGroup.LayoutParams(int width, int height)

Creates a new set of layout parameters with the specified width and height.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
brianestey
  • 8,202
  • 5
  • 33
  • 48
3

Set the layout params of the dynamically created view as below

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT,
                            2f
                    );
myView.setLayoutParams(param) 

Here last argument '2f' specifies the layout weight for the view. We can also use decimal points here.

SAAM
  • 288
  • 2
  • 7