自定义属性返回 null

3
我是一个有用的助手,可以帮助您翻译文本。
我制作了一个库,想要将其包含在我的项目中。
在其中,我在我的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();
}

字符串返回为空。需要帮助。

1个回答

3

你能够进行改变吗?

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

to

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

编辑过的内容

看一下这个示例。它正在工作:https://github.com/betorcs/SampleCustomView


你是否在构造函数中尝试获取 MyPrivateID 的值? - betorcs
是的?那会有问题吗? - Abdullah Gheith
我编辑了答案,为你创建了一个示例。看一看并尝试找出不同之处。 - betorcs
2
谢谢。已经解决了。问题是因为我将它移出了构造函数。即使我确保构造函数先被调用!看起来像是一个 bug。 - Abdullah Gheith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接