Android开发如何将vw测量单位转换为dp?50vw对应dp计算咨询
问题解答
你的理解存在两处核心错误
- 第一是vw的定义混淆:vw是视口宽度(Viewport Width)的百分比单位,50vw对应设备可用宽度的50%,和高度没有任何关系。你当前设备的最大宽度是1079dp,就算要硬编码也应该用1079/2≈539.5dp,你用设备高度399dp计算完全搞错了参照维度。
- 第二是硬编码适配逻辑不成立:你计算出的数值只适配你当前这一台设备,Android设备屏幕尺寸、分辨率千差万别,不同设备的屏幕总宽度dp值完全不同,硬写死固定dp值到其他设备上根本达不到50vw的效果。
正确实现方案
Android原生不需要手动将vw转换为dp,直接用百分比布局属性即可实现宽度占屏幕50%的需求,推荐用ConstraintLayout实现,修改后的代码如下:
<FrameLayout 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"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintWidth_percent="0.5"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World!" android:textAlignment="center" /> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout> </FrameLayout>
核心是给需要占50%宽度的LinearLayout设置layout_width="0dp",再加上app:layout_constraintWidth_percent="0.5"属性,同时通过上下左右约束到父布局实现居中,就可以在所有设备上都达到宽度占屏幕50%、全局居中的效果。
内容的提问来源于stack exchange,提问作者Moh
相关产品推荐
相关产品推荐

