android stdio 的布局属性
1.ImageView
代码
<ImageViewandroid:id="@+id/my_image_view"android:layout_width="0dp"android:layout_height="0dp"android:src="@drawable/img"android:scaleType="fitCenter"android:contentDescription="@string/image_desc"app:layout_constraintStart_toStartOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintTop_toTopOf="parent"app:layout_constraintBottom_toBottomOf="parent"app:layout_constraintWidth_percent="1.5"app:layout_constraintHeight_percent="0.5"app:layout_constraintDimensionRatio="H,15:9"/>
一、基本属性
1. android:id="@+id/my_image_view"
含义:为组件设置唯一标识符
必要性:★☆☆☆☆ (非必须)
说明:
- 只有在代码中需要操作此组件时才需要设置(如动态修改图片)
- 在图片的Attributes面板中可见(
my_image_view
)
关联关系:与Java/Kotlin代码有交互时需要
2. android:layout_width="0dp"
和 android:layout_height="0dp"
含义:尺寸约束模式(ConstraintLayout专用)
必要性:★★★★☆ (布局关键)
说明:
0dp
= “match_constraint”- 在图片的预览区域表现为根据约束自动调整尺寸
- 必须配合约束属性使用(如下面的
constraint*
属性)
关联关系:强依赖constraintWidth/Height_percent
3. android:src="@drawable/img"
含义:设置图片资源
必要性:★★★★★ (必须)
说明:
@drawable/img
对应res/drawable目录下的图片文件- 在图片的预览区可见显示的粉色卡通图
关联关系:强关联图片文件和scaleType
属性
4. android:scaleType="centerCrop"
含义:图片缩放模式
必要性:★★★★☆ (建议设置)
说明:
centerCrop
:保持比例拉伸填满控件,居中裁剪多余部分- 在Attributes面板有单独选项
- 若未设置,可能导致图片变形
关联关系:强依赖layout_width/height
5. android:contentDescription="@string/image_desc"
含义:无障碍内容描述
必要性:★★★☆☆ (非必须但建议)
说明:
- 需在
res/values/strings.xml
中定义具体文字 - 在Attributes面板的"accessibility"区域设置
关联关系:无强关联
6. 约束属性组
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
含义:组件定位约束
必要性:★★★★★ (必须)
说明:
- 在图片的设计视图表现为组件四角与父容器连接
- 实现居中显示的核心逻辑
关联关系:强依赖父容器(ConstraintLayout)
7. 百分比约束
app:layout_constraintWidth_percent="0.8"
app:layout_constraintHeight_percent="0.5"
含义:基于父容器尺寸的百分比
必要性:★★★★☆ (推荐)
说明:
- 在Attributes面板"Layout"部分设置
0.8
=80%父容器宽度,0.5
=50%高度
关联关系:强依赖父容器尺寸
8. app:layout_constraintDimensionRatio="H,16:9"
含义:固定宽高比
必要性:★★☆☆☆ (可选)
说明:
H,16:9
:以高度为基准,宽高比16:9- 可替换为
W,16:9
(以宽度为基准)
关联关系:与百分比约束冲突(二选一)
二、 属性关系矩阵
属性 | 是否必须 | 依赖组件 | 冲突属性 |
---|---|---|---|
id | 可选 | 无 | 无 |
layout_width/height | 必需 | ConstraintLayout | 无 |
src | 必需 | 图片资源文件 | 无 |
scaleType | 推荐 | 尺寸属性 | 无 |
contentDescription | 可选 | 无 | 无 |
constraint*定位 | 必需 | 父容器 | 绝对定位 |
constraint*percent | 推荐 | 父容器尺寸 | 固定比例 |
dimensionRatio | 可选 | 无 | 百分比约束 |
三、 使用建议(根据图片优化)
- 优先选择百分比约束(非固定比例时)
- 删除预览专用属性:
tools:layout_editor_absoluteX="..." tools:layout_editor_absoluteY="..."