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?
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?
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)
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.
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.