【问题标题】:Planning custom screen layout for multiple screens为多个屏幕规划自定义屏幕布局
【发布时间】:2019-08-04 19:09:37
【问题描述】:

我有一个带有width="match_parent" 的自定义布局。布局由中心的大圆圈和旁边的小圆圈组成。

在我的屏幕上,我找到了我喜欢的尺寸,现在我想让它在所有设备上看起来都相似。

我的设备是 Galaxy S8,显示指标报告为:

DisplayMetrics {
    density=3.5,
    width=1440,
    height=2960,
    scaledDensity=2.8,
    xdpi=562.707,
    ydpi=565.293
}

据我所知,我有 411dp 的宽度可用。

对于我有的尺寸

  • 中心半径为 110dp 的大圆圈。
  • 旁边的小圆圈半径为 21dp。
  • 它们之间的距离为 20dp。

现在我想知道我该怎么做。我有两个选择。首先是为其他屏幕密度创建单独的值,或者只是将此尺寸转换为百分比并以编程方式进行布局。

我对第一个选项的问题是某些设备(例如我的)具有屏幕缩放功能,它会更改 scaledDensity 使其看起来完全不同。

【问题讨论】:

    标签: android android-layout dpi android-screen-support


    【解决方案1】:

    你可以支持不同的屏幕尺寸使用ConstraintLayout:

    ConstraintLayout 允许您创建具有平面视图层次结构(无嵌套视图组)的大型复杂布局。它与RelativeLayout 类似,所有视图都根据兄弟视图和父布局之间的关系进行布局,但它比RelativeLayout 更灵活,更易于与Android Studio 的布局编辑器一起使用。

    您可以使用这些属性来指定视图大小(以百分比为单位):

    app:layout_constraintWidth_percent=".5"
    app:layout_constraintHeight_percent=".5"
    

    例如,单个按钮的高度和宽度都等于屏幕的 50%:

    <?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">
    
    
    <Button
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent=".5"
        app:layout_constraintHeight_percent=".5"/>
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    它看起来像这样:

    还有一点,因为不同的手机有不同的屏幕尺寸,所以您最好不要在视图中使用固定尺寸尺寸(例如50dp)。

    我可以推荐使用 ConstraintLayoutguidelinesChains 来支持不同的屏幕尺寸(除了我上面提到的 - app:layout_constraintWidth_percentapp:layout_constraintHeight_percent)。

    【讨论】:

    • 这是一种有趣的方法,因为我以前从未尝试过 ConstraintLayout。 layout_constraintHeight_percent 可以和宽度一样吗?
    • 是的,如果你想显示一个正方形,你可以使用app:layout_constraintDimensionRatio="1:1"。从阅读文档开始。它真的是用户友好的
    • 这听起来不像我打算做的那样痛苦,所以我至少会尝试一下。接受答案:)
    • 如果您有任何问题,请随时在我的linkedin 中写信给我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多