I am having trouble finding out how to set layout properties in my code. My controls are being generated at runtime so I can't set the layout in my xml.
I would like to be able to set properties such as
android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_weight="1"
However I can't find any documentation or examples on how to do this in code. Is it possible with the current version of Mono for Android?
Relevant thread on the Mono for Android mailing list.
Many of the constructors take an IAttributeSet instance, so (worst case) you could always provide the XML custom attributes through that parameter when invoking the e.g. RelativeLayout(Context, IAttributeSet) constructor.
Resource attributes are handled specifically in Java code, and thus can potentially vary from one class to another. For example, the RelativeLayout constructor implementation.
Because of this, attributes can (and will be) specific to a given type. For example, as best as I can tell from quickly perusing the Android source, it's not valid for a type to have both
android:layout_alignParentBottom
andandroid:layout_weight
attributes, as android:layout_alignParentBottom appears to be specific to theRelativeLayout
type, while android:layout_weight is specific to LinearLayout, and there is no inheritance relationship betweenRelativeLayout
andLinearLayout
.That said, to programmatically assign the
android:layout_alignParentBottom
property, it looks like you'd want to do:This uses the RelativeLayout.LayoutParams.AddRule method to enable the layout option. The
int
cast is necessary because we didn't realize thatAddRule()
should take aLayoutRules
enum; oops.To programmatically assign the
android:layout_alignParentRight
property:As noted above, it appears that android:layout_weight is specific to
LinearLayout
, so we can't useRelativeLayout.LayoutParams
to set this. Instead, we need to useLinearLayout.LayoutParams
to set the LinearLayout.LayoutParams.Weight property: