Android布局文件xml中的android、app、tools

在安卓开发中,我们经常会在 xml 布局文件中会看到 xmlns:android、xmlns:app、xmlns:tools 这样的东西,就像下面这样;

<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"
              
     <ImageView
        android:id="@+id/head_portrait"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        app:showAsAction="never"
        tools:srcCompat="@drawable/head" />

</LinearLayout>

那它们有什么用和区别呢?

首先,xmlns 是 xml namespace 的缩写,意思是 xml 命名空间。

  1. xmlns:Android 命名空间用于访问和使用 Android 平台提供的属性。如上面使用到的 android:id、android:layout_width、android:layout_height 等都是安卓平台提供的属性。

  2. xmlns:app (或 xmlns:‘customname’)命名空间用于访问在应用程序范围内定义的自定义属性。app 命名空间并不特定于库,它用于应用程序中定义的所有属性,无论是你通过代码还是通过导入的库,它是一个全局命名空间可用于你自定义的属性,即 android 未定义的属性。

  3. xmlns:tools tools可以告诉Android Studio,哪些属性在运行的时候是被忽略的,只在设计布局的时候有效。tools可以覆盖 android 的所有标准属性,将android: 换成 tools: 即可;同时在运行的时候就连 tools: 本身都是被忽略的,不会被带进 apk 中。

    安卓开发中,在写布局代码的时候,ide可以看到布局的预览效果。但是有些效果则必须在运行之后才能看见,比如这种情况:TextView在xml中没有设置任何字符,而是在 activity 中设置了 text。因此为了在 ide 中预览效果,你必须在 xml 中为 TextView 控件设置 android:text 属性,为了减轻工作量和开发负担,这里就要使用 tools:text 辅助属性。


参考:

xml中的android、app、tools你真的了解吗
What is the ‘app’ Android XML namespace
Android布局文件中的xmlns:tools作用以及用法

猜你喜欢

转载自blog.csdn.net/qq_33697094/article/details/131122979