我有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使其看上去完全不同。

最佳答案

您可以使用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>


它看起来像这样:

android - 规划多个屏幕的自定义屏幕布局-LMLPHP

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

我可以建议将ConstraintLayoutguidelinesChains一起使用以支持不同的屏幕尺寸(除了我上面提到的-app:layout_constraintWidth_percentapp:layout_constraintHeight_percent)。

10-07 19:33
查看更多