styles.xml中的自定义属性

我创build了一个自定义小部件,并在layout.xml中声明它。 我还在attr.xml中添加了一些自定义属性。 但是,当试图在styles.xml中声明这些属性时,它会给我No resource found that matches the given name: attr 'custom:attribute'.

我已经在styles.xml中的所有标记中放入了xmlns:custom="http://schemas.android.com/apk/res/com.my.package" ,包括<?xml><resources><style> ,但它仍然给我同样的错误,它找不到我自定义的XML名称空间。

但是,我可以使用我的命名空间在layout.xml中为视图手动分配属性,所以名称空间没有任何问题。 我的问题在于使styles.xml知道我的attr.xml。

我想到了! 答案是不要在样式中指定名称空间。

 <?xml version="1.0" encoding="utf-8" ?> <resources xmlns:android="http://schemas.android.com/apk/res/android"> <style name="CustomStyle"> <item name="android:layout_width">wrap_content</item> <item name="android:layout_height">wrap_content</item> <item name="customAttr">value</item> <!-- tee hee --> </style> </resources> 

上面的答案是为我工作,我尝试了一个小改变,我声明资源元素的一个类styleable。

 <declare-styleable name="VerticalView"> <attr name="textSize" format="dimension" /> <attr name="textColor" format="color" /> <attr name="textBold" format="boolean" /> </declare-styleable> 

声明样式中name属性引用了一个类名,所以我有一个视图类调用“com.my.package.name.VerticalView”,它表示这个声明必须在VerticalView或VerticalView的子类中使用。 所以我们可以像这样声明样式:

 <resources> <style name="verticalViewStyle"> <item name="android:layout_width">match_parent</item> <item name="android:layout_height">36dip</item> <item name="textSize">28sp</item> <!-- not namespace prefix --> <item name="textColor">#ff666666</item> <item name="textBold">true</item> </style> </resources> 

这就是为什么我们没有在资源元素声明名称空间,它仍然工作。

Styler和vince的修改为我工作。 我想指出@文斯的解释可能不完全准确。

为了testingdeclare-styleable的name属性与自定义视图类的名称是否允许我们访问没有名称空间的自定义属性的假设,我更改了declare-styleable的名称(自定义视图名为TestViewFont

 <declare-styleable name="TextViewFont2"> <attr name="font" format="integer"/> </declare-styleable> 

然后,我改变了自定义视图中的obtainStyledAttributes调用来反映这一点:

 TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TextViewFont2, 0, 0); 

代码仍然运行。 所以我不认为这是它所命名的类的declare-styleable的反思。

因此,我引导人们相信,任何自定义属性都可以用来声明一个没有引用名称空间的样式。

无论如何,感谢所有帮助人,它解决了我的问题。

如果它帮助别人,我的错误是,我的自定义视图类调用AttributeSet.getAttributeValue例如

 String fontName = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "customFont"); 

…这导致我的自定义属性没有被读入我的自定义视图。

解决的办法是在我的自定义视图中使用obtainStyledAttributes

  TypedArray styleAttrs = context.obtainStyledAttributes(attrs, R.styleable.MyTextViewStyleable); String fontName = styleAttrs.getString(R.styleable.MyTextViewStyleable_customFont); 

这个工作正常的一个提示是你可以通过Ctrl / Apple +单击R.styleable.MyTextViewStyleable_customFont直接进入你的attrs.xml定义。

我花了一段时间来发现我的代码和其他示例之间的这种关键区别,因为自定义属性直接通过布局XML(而不是通过样式)传递时工作正常。