android – monodroid / xamarin自定义属性使用ObtainStyledAttributes为空

前端之家收集整理的这篇文章主要介绍了android – monodroid / xamarin自定义属性使用ObtainStyledAttributes为空前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试将自定义属性从父布局传递到子布局.

从ObtainStyledAttributes()返回的TypedArray似乎没有我创建的自定义属性的相应自定义值,尽管我可以将它们的ID映射到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" />

查看课程:

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

解决方法

我认为问题在于您如何指定xmlns:自定义命名空间.您需要在已有的字符串末尾添加应用程序命名空间,以便:
xmlns:custom="http://schemas.android.com/apk/res/my.awesome.namespace"

您还需要为Android项目定义AndroidManifest.xml,您已在其中定义了相同的命名空间.

线条:

int[] styleAttrs = Resource.Styleable.HeaderView;
TypedArray a = context.ObtainStyledAttributes(attrs,styleAttrs);

看起来有点奇怪,我会写:

var a = context.ObtainStyledAttributes(attrs,Resource.Styleable.HeaderView);

特别是如果你以后不使用styleAttrs.

编辑:自Android SDK rev 17以来,可以使用:

xmlns:custom="http://schemas.android.com/apk/res-auto"

而不是必须编写整个命名空间.

原文链接:https://www.f2er.com/android/318034.html

猜你在找的Android相关文章