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

问题描述 投票:0回答:1

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

attrs.xml文件夹中res文件的内部,我这样定义了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. [The android documentation uses a custom URI like I defined above,为什么我这样做时android studio会引发错误?
android namespaces
1个回答
1
投票

您不需要自定义名称空间。如果您的customviews包包含在您的项目中,则其attrs将合并到您的项目中,并且您可以仅对它们使用app:。

© www.soinside.com 2019 - 2024. All rights reserved.