为多个屏幕规划自定义屏幕布局

Planning custom screen layout for multiple screens

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

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

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

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

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

对于尺寸我有

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

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

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

ConstraintLayout allows you to create large and complex layouts with a flat view hierarchy (no nested view groups). It's similar to RelativeLayout in that all views are laid out according to relationships between sibling views and the parent layout, but it's more flexible than RelativeLayout and easier to use with Android Studio's Layout Editor.

您可以使用这些属性以百分比指定您的视图大小:

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)。

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