繁体   English   中英

在android中使用自定义属性和命名空间

[英]Using custom attributes and namespace in android

包结构基本上是: app>src>main>com.example.customviews ,其中存在一个包含CustomView.java文件的view文件夹。

res文件夹中的attrs.xml文件中,我定义了一个stylable

<resources>
<declare-styleable name="PieChart">
        <attr name="showText" format="boolean"/>
        <attr name="labelPosition" format="enum">
            <enum name="left" value="0"/>
            <enum name="right" value="1"/>
        </attr>
    </declare-styleable>  
</resources>

activity_main.xmlMainactivity.java也在com.example.customviews目录中)我试图为我的自定义属性定义一个命名空间,如下所示:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:gravity="center">

...
...
...  

</LinearLayout>  

但是对于定义的命名空间,android 在编辑器中给了我以下错误消息:

在 Gradle 项目中,始终使用http://schemas.android.com/apk/res-auto来减少自定义属性... (Ctrl+F1)
检查信息:在 Gradle 项目中,最终 APK 中使用的实际包可能会有所不同; 例如,您可以在一个版本而不是另一个版本中添加 .debug 包后缀。 因此,您不应该对资源中的应用程序包进行硬编码; 相反,使用特殊的命名空间http://schemas.android.com/apk/res-auto这将导致工具为资源找出正确的命名空间,而不管构建期间使用的实际包。

这带来了以下两个问题:

  1. URI http://schemas.android.com/apk/res-auto什么作用,它是由 android 动态解析的吗? app命名空间一样,它被解析为一个 URI,而对于custom命名空间,它被用于另一个?
  2. android 文档使用了我上面定义的自定义 URI ,为什么我这样做时 android studio 会引发错误?

您不应该需要自定义命名空间。 如果您的项目中包含您的 customviews 包,则其属性将合并到您的项目中,您只需使用 app: 即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM