How to set android: layout_weight and android: layout_width in code?

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

Link: XML table layout? Two lines of EQUAL-width filled with buttons with the same width?

+6
source share
3 answers

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 constants. But fixed pixels are a bad idea for Android because there are so many devices.

You can calculate pixels from dp size, although this is normal:

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

(Here: convert 10dp to pixel value)

+16
source

Try

 setLayoutParams(new LayoutParams(width, height)) 

The docs for the designer say:

 ViewGroup.LayoutParams(int width, int height) 

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

+1
source

Set the layout options for the dynamically created view below

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

Here, the last argument “2f” indicates the weight of the layout to represent. Here we can also use decimal points.

+1
source

Source: https://habr.com/ru/post/897087/


All Articles