首页 > 解决方案 > 如何在android中将vw测量转换为dp?

问题描述

Android Studio 代码片段

我有一个 android 设备,它的最大宽度和高度以 dp 单位指定。

我想创建一个必须垂直和水平居中的 LinearLayout,其高度必须在 wrap_content 长度和宽度中以占据50vw单位。我知道50vw意味着占据宽度的50%,但我很难将这个50vw宽度要求转换为dp尺寸。那么我应该将布局宽度硬编码为 399/2 dp = 199.5dp,它应该等于50vw吗?或者我是否正确地将设备的最大宽度分成两半以匹配50vw的要求?

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="199.5dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Hello World!"
            android:textAlignment="center" />
    </LinearLayout>

</LinearLayout>

如果我的理解不正确,请告诉我?谢谢。

标签: javaandroidandroid-layoutandroid-activityandroid-linearlayout

解决方案


如果您正在使用LinearLayout并且希望宽度为父级的 50%,则可以使用orientation="horizontal", weightSum, layout_weight. 这是一个例子

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="2">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="80dp"
        android:layout_weight="1"
        android:background="#f00" />

</LinearLayout>

如果您使用ConstraintLayout,您还可以使用 with percent 将宽度设置为父宽度的 50% Guideline,或者layout_constraintHorizontal_weight


推荐阅读