Trying to pass a custom attribute from a parent layout to a child layout.
The TypedArray returned from ObtainStyledAttributes() doesn't seem to have the corresponding custom values for the custom properties I've created, although I can map their IDs to the values in Resource.designer.
Attr.xml:
<resources>
<declare-styleable name="HeaderView">
<attr name="bgcolor" format="color" />
<attr name="testing" format="string" />
</declare-styleable>
Main.xaml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<views.HeaderView
android:id="@+id/hdrWatchList"
android:layout_width="fill_parent"
android:layout_height="20.0dp"
custom:bgcolor="@color/blue"
custom:testing="testing text buddy" />
View Class:
public HeaderView (Context context, IAttributeSet attrs) :
base (context, attrs)
{
int[] styleAttrs = Resource.Styleable.HeaderView;
TypedArray a = context.ObtainStyledAttributes(attrs, styleAttrs);
string sid = a.GetString(Resource.Styleable.HeaderView_testing);
int id = a.GetColor(Resource.Styleable.HeaderView_bgcolor, 555);
Log.Info( "testing", "resource sid : " + sid); // RETURNS ''
Log.Info( "testing", "resource id : " + id); // RETURNS DEF 555
I think the issue lies with how you specified your xmlns:custom
namespace. You need to add your applications namespace at the end of the string your already have like so:
xmlns:custom="http://schemas.android.com/apk/res/my.awesome.namespace"
You also need to have a AndroidManifest.xml
defined for your Android project, where you have defined the same namespace.
Also the lines:
int[] styleAttrs = Resource.Styleable.HeaderView;
TypedArray a = context.ObtainStyledAttributes(attrs, styleAttrs);
Look a bit strange to me and I would just write:
var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.HeaderView);
Especially if you are not using styleAttrs
later on.
EDIT: since Android SDK rev 17 it is possible to use:
xmlns:custom="http://schemas.android.com/apk/res-auto"
instead of having to write the entire namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With