Android UI设计XML中xmlns、android、tools、app标识含义解答
Android布局XML命名空间相关标识说明
首先明确:android:layout_width这类写法里的前缀不是代码中的实体对象,不存在“android对象的属性”这种对应关系,这些前缀是XML命名空间机制的简写,作用是区分不同来源的属性,避免重名冲突。
xmlns的作用
xmlns是XML Namespace(XML命名空间)的声明关键字,固定写法为xmlns:自定义前缀="命名空间唯一标识",声明后当前XML文件内所有带该前缀的属性,都会被解析到对应的属性集合下。- 布局文件里的命名空间通常统一声明在根布局节点上,作用域覆盖整个XML文件。
三个常用前缀的具体含义
android前缀
- 对应命名空间:
http://schemas.android.com/apk/res/android - 归属:Android系统原生SDK内置的标准属性集合
- 用途:所有系统原生控件属性、所有控件通用的基础属性都在这个集合下,比如示例代码里的
layout_width、layout_height、text都是系统定义的标准属性,必须加android:前缀。
app前缀
- 对应命名空间:
http://schemas.android.com/apk/res-auto - 归属:项目自身、引入的第三方库、AndroidX扩展组件定义的自定义属性集合
- 用途:不属于系统原生框架的扩展属性都归在这个命名空间下,构建工具编译时会自动扫描项目所有依赖的自定义属性做匹配。比如示例中ConstraintLayout的约束属性
layout_constraintTop_toTopOf是AndroidX库新增的,就需要加app:前缀。
tools前缀
- 对应命名空间:
http://schemas.android.com/tools - 归属:专门给Android Studio等开发工具使用的属性集合
- 用途:这类属性仅在开发阶段的预览界面生效,打正式APK时会被完全移除,不会影响线上运行逻辑。比如示例里的
tools:context=".MainActivity"是告诉开发工具当前布局关联的Activity类,方便工具做预览主题适配、代码关联跳转;你也可以用tools:text给预览界面加测试占位文本,不会把测试内容带到正式包里。
示例代码参考
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
内容的提问来源于stack exchange,提问作者Ruipeng Dong
相关产品推荐
相关产品推荐

