自定义属性返回null

时间:2017-03-07 19:38:23

标签: android android-xml

我创建了一个我想要包含在我的项目中的库。

在那里,我在我的attr.xml中有这个:

 <declare-styleable name="MyCustomView">
    <attr name="MyPrivateID" format="string"/>
</declare-styleable>

我在我的应用程序中包含了库,它工作正常。但我无法撤销我的自定义属性。

这是我的activity_main.xml

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

<something.myown.MyCustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:MyPrivateID="GjM4X9QfK2VT05BKlEyffkAKGLU=dhbdsljhbdDjTchvNTQwMg=="/>

在MyCustomView.java中,我有:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
try {
    String string = a.getString(R.styleable.MyCustomView_MyPrivateID);
    return string;
} finally {
    a.recycle();
}

不知何故,字符串返回null。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

你能改变吗?

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.HalalAdView);

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);

<强> EDITED

看一下这个样本。它工作https://github.com/betorcs/SampleCustomView