Andorid车机UI适配,AndroidUI图px的单位,如何适配1920x720,PPI100的屏幕设备
在 Android 开发中,针对 1920×720 分辨率、PPI 100 的屏幕设备进行 UI 适配,需要综合考虑 像素密度(PPI)、屏幕尺寸 和 Android 的密度无关像素(dp) 体系。以下是完整的适配方案:
📌 1. 关键概念理解
(1) 屏幕参数计算
-
分辨率:1920×720(横向像素 × 纵向像素)
-
PPI(Pixels Per Inch):100(每英寸像素数)
-
屏幕尺寸(对角线):
尺寸=19202+7202100≈2048100=20.48英寸尺寸=10019202+7202≈1002048=20.48英寸(假设是 16:9 屏幕)
(2) Android 密度分类
| PPI 范围 | 密度类型 | Density(density) | 比例 |
|---|---|---|---|
| 0 ~ 120 | ldpi | 0.75x | 3:4 |
| 120 ~ 160 | mdpi | 1x (基准) | 1:1 |
| 160 ~ 240 | hdpi | 1.5x | 3:2 |
| 240 ~ 320 | xhdpi | 2x | 2:1 |
| 320 ~ 480 | xxhdpi | 3x | 3:1 |
| 480+ | xxxhdpi | 4x | 4:1 |
本例:PPI=100 → 属于 ldpi(低密度),density=0.75。
📌 2. 核心适配方案
(1) 使用 dp 替代 px
换算公式:
dp=pxdensity=px0.75dp=densitypx=0.75px
-
示例:设计稿中
100px→ 代码中应写133.33dp(因为100 / 0.75 ≈ 133.33)。
<Buttonandroid:layout_width="133dp" <!-- 设计稿 100px -->android:layout_height="67dp" <!-- 设计稿 50px -->android:text="按钮" />
(2) 使用 sp 设置字体大小
<TextViewandroid:textSize="16sp" /> <!-- 会随系统字体缩放 -->
📌 3. 针对 1920×720 (PPI 100) 的特殊处理
(1) 创建 values-ldpi 资源目录
在 res/values-ldpi/dimens.xml 中定义尺寸:
<resources><!-- 设计稿 100px → 实际 133.33dp --><dimen name="button_width">133dp</dimen><dimen name="button_height">67dp</dimen> </resources>
布局中使用:
<Buttonandroid:layout_width="@dimen/button_width"android:layout_height="@dimen/button_height" />
(2) 使用 smallestWidth (sw) 适配
计算最小宽度(sw):
sw=min(1920,720)density=7200.75=960dpsw=densitymin(1920,720)=0.75720=960dp
创建 res/values-sw960dp/dimens.xml 存放适配尺寸。
📌 4. 百分比布局(推荐 ConstraintLayout)
<androidx.constraintlayout.widget.ConstraintLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"><Buttonandroid:layout_width="0dp"android:layout_height="wrap_content"app:layout_constraintWidth_percent="0.5" <!-- 宽度占屏幕 50% -->app:layout_constraintStart_toStartOf="parent"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
📌 5. 代码动态计算(适用于特殊场景)
kotlin
// 将 px 转换为 dp
fun pxToDp(px: Int, context: Context): Int {val density = context.resources.displayMetrics.densityreturn (px / density).toInt()
}// 示例:设计稿 100px → 动态设置
button.layoutParams.width = pxToDp(100, context)
📌 6. 测试与验证
-
使用 Android Studio 的模拟器,选择自定义设备(1920×720,PPI 100)。
-
检查
DisplayMetrics:kotlin
val metrics = resources.displayMetrics Log.d("Screen", "密度: ${metrics.density}dpi, 宽度: ${metrics.widthPixels}px")
🚀 最佳实践总结
| 方法 | 适用场景 | 备注 |
|---|---|---|
dp / sp | 通用适配 | 优先使用 |
values-ldpi | 低密度设备(PPI=100) | 覆盖 density=0.75 的情况 |
| 百分比布局 | 复杂 UI | ConstraintLayout + Guideline |
动态计算 dp | 特殊需求(如游戏 UI) | 代码中转换 px → dp |
关键点:
-
PPI=100 →
ldpi→density=0.75。 -
设计稿
px需按dp = px / 0.75转换。 -
优先用
ConstraintLayout百分比布局,避免硬编码尺寸。
