Setting layout properties in code at runtime

2019-09-01 13:20发布

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?

1条回答
放我归山
2楼-- · 2019-09-01 14:15

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 and android:layout_weight attributes, as android:layout_alignParentBottom appears to be specific to the RelativeLayout type, while android:layout_weight is specific to LinearLayout, and there is no inheritance relationship between RelativeLayout and LinearLayout.

That said, to programmatically assign the android:layout_alignParentBottom property, it looks like you'd want to do:

// Get a RelativeLayout.LayoutParams instance
// Option 1, if you have an existing RelativeLayout instance already:
var p = (RelativeLayout.LayoutParams) layout.LayoutParameters;

// Option 2: if you don't.
var p = new RelativeLayout.LayoutParams (context, null);

// Enable layout_alignParentBottom:
p.AddRule ((int) LayoutRules.AlignParentBottom);

This uses the RelativeLayout.LayoutParams.AddRule method to enable the layout option. The int cast is necessary because we didn't realize that AddRule() should take a LayoutRules enum; oops.

To programmatically assign the android:layout_alignParentRight property:

p.AddRule ((int) LayoutRules.AlignParentRight);

As noted above, it appears that android:layout_weight is specific to LinearLayout, so we can't use RelativeLayout.LayoutParams to set this. Instead, we need to use LinearLayout.LayoutParams to set the LinearLayout.LayoutParams.Weight property:

// Just like before, but get a LinearLayout.LayoutParams instance
// Option 1, if you have an existing LinearLayout instance already:
var p = (LinearLayout.LayoutParams) layout.LayoutParameters;

// Option 2: if you don't.
var p = new LinearLayout.LayoutParams (context, null);

// Enable layout_weight:
p.Weight = 1.0f;
查看更多
登录 后发表回答