我试图以编程方式获取自定义小部件的自定义属性的值。
小部件扩展了linearlayout,我定义了如下自定义属性:

<declare-styleable name="CustomWidget">
    <attr name="customProperty" format="string" />
</declare-styleable>

当前正在尝试访问“customproperty”的值,如下所示:
public CustomWidget(Context context, IAttributeSet attrs)
    : base(context, attrs)
{
    var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.CustomWidget);
    var s = a.GetString(Resource.Styleable.CustomWidget_customProperty);
}

我也尝试过在onfinishInflate()方法中调用这段代码,但没有成功。
值得一提的是,这个小部件位于一个单独的android库项目中。

最佳答案

我在MonoDroid.ActionBar中的工作很好。因此,在尝试使用自定义属性时,可能会陷入困境。您必须记住在xml中声明xmlns名称空间,并将其引用到应用程序的正确名称空间。
因此,假设您的名称空间是My.Awesome.App其中包含CustomWidget的某个位置,那么您的axml布局可能如下所示:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cs="http://schemas.android.com/apk/res/my.awesome.app"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <my.awesome.app.CustomWidget
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        cs:customProperty="Awesome!"
        />
</LinearLayout>

请注意,已经声明了一个csxmlns名称空间,这在CustomWidget中的axml声明中用于将字符串Awesome!传递到自定义布局。
现在您应该能够在customProperty的构造函数中获取CustomWidget
//Custom Attributes (defined in Attrs.xml)
var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.CustomWidget);

var awesomeProperty = a.GetString(Resource.Styleable.CustomWidget_customProperty);
if (null != awesomeProperty)
    //do something with it...

//Don't forget to recycle it
a.Recycle();

10-07 13:53
查看更多