首页 > 解决方案 > 如何针对不同的屏幕尺寸动态调整文字大小和边距?

问题描述

我正在使用ConstraintLayout. 它可以在不同的屏幕尺寸上正确显示,但是,我希望 textviews 增加元素之间的尺寸和间距,以利用更大屏幕手机上的更大屏幕空间。

我读过您可以为不同的密度或大小(xxhdpi、xhdpi)创建不同的 XML 布局,但我认为ConstraintLayout相对于相对布局的主要优势之一是它会自动调整间距/大小。您可以使用约束布局来做到这一点,还是需要为每个屏幕尺寸/密度创建单独的 xml 布局?谢谢!

<android.support.constraint.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"
    tools:context=".MainActivity"
    tools:layout_editor_absoluteY="81dp">

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="19dp"
        android:backgroundTint="@color/colorAccent"
        app:layout_constraintBottom_toTopOf="@+id/inView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/lbsView"
        app:layout_constraintTop_toTopOf="parent" />


    <TextView
        android:id="@+id/weightView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="27dp"
        android:layout_marginTop="21dp"
        android:layout_marginEnd="14dp"
        android:text="Weight:"
        android:textSize="26sp"
        app:layout_constraintEnd_toStartOf="@+id/weight"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

这是我的约束布局示例。

标签: androidandroid-layout

解决方案


将您的边距值放入dimens.xml,从那里您可以调整不同屏幕尺寸的尺寸values-hdpi,例如 values-xhdpi`,..

values-hdpi/dimens.xml

<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <dimen name="spinner_margin_top">16dp</dimen>
</resources>

values-xhdpi/dimens.xml

<?xml version="1.0" encoding="UTF-8"?>
<resources>
  <dimen name="spinner_margin_top">20dp</dimen>
</resources>

在你的 xml 文件中:

<Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/spinner_margin_top"
        .... />

推荐阅读