在安卓系统中,如何在styles.xml中使用自定义属性?

5
我做了一个自定义属性的样式,如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="EffectsTextView">        
        <attr name="strokeWidth" format="float" />
        <attr name="strokeMiter" format="float" />
        <attr name="strokeColor" format="color" />        
    </declare-styleable>
</resources>

在布局文件中,我可以使用这个自定义属性为这个属性分配一个命名空间:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:effects="http://schemas.android.com/apk/res-auto/com.base.view.EffectsTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#40000000" >

 <com.base.view.EffectsTextView
        android:id="@+id/textView1"
        android:layout_width="290dip"
        android:layout_height="80dip"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="16dip"
        android:gravity="center"
        android:text="SETTINGS"
        android:textSize="44dip"
        android:textStyle="bold"  
        effects:strokeWidth="10"  />    <--- custom tag "effects"

然而,它没有在styles.xml中识别这个自定义标签。

<style name="EffectsHeaderTextStyle">
     <item name="effects:strokeWidth">10</item>
</style>

错误:找不到与给定名称effects匹配的资源,虽然我在RelativeLayout文件中使用了相同的命名空间。

有什么想法吗?谢谢

2个回答

23

这完全可行,但我发现在 IntelliJ 中会出现“声明的命名空间未被使用”的警告。我移除了 xmlns 声明,它仍然可以正常工作。在 IntelliJ 中看来,自定义视图的属性不需要命名空间。 - Tonithy

0

Gradle不建议在xmln:中使用实际的包名。
在Gradle项目中,最终APK中使用的实际包名可能会有所变化;例如,在一个版本中添加.debug包后缀,在另一个版本中则没有。因此,您不应该在资源中硬编码应用程序包名;而是使用特殊命名空间http://schemas.android.com/apk/res-auto,这将使工具在构建期间找到正确的资源命名空间,而不管实际包名如何。


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