【问题标题】:Keep text centered in parent in ConstraintLayout in Android在Android的ConstraintLayout中保持文本居中在父级中
【发布时间】:2020-04-05 16:52:47
【问题描述】:

我想在Android的ConstraintLayout中实现一个非常简单的顶栏布局:

有一个返回按钮(可以隐藏),有一个右键(可以隐藏),中间有一个文本标题。 最重要的是,我想让文本在父级居中。

但是,当我绑定视图的边框时,标题文本会从中心推送,因为左右视图的大小不同:

如您所见,TITLE 不在父级的中心。显然,工作解决方案中的文本也不应该相互重叠,并且标题应该是省略号的。所以这就像一个从两边推的“高级障碍”——越大的会迫使标题变小,但标题总是在中间。

这样做的一种方法是制作等宽的左右视图,其余的将提供给标题视图,但是我找不到在不同区域制作两个等宽视图的方法。

这在ConstraintLayout 中是否可行?在 iOS 的 Autolayout 系统中很容易做到,但它比 Android 的 ConstraintLayout 强大得多。

【问题讨论】:

    标签: android android-constraintlayout


    【解决方案1】:

    但是我找不到在等宽的不同区域创建两个视图的方法

    如果你想实现这样的目标,你可以使用:

    app:layout_constraintWidth_percent="0.x" 根据屏幕尺寸告诉您的视图尺寸(并保持响应)。

    例如像这样的东西(我用支持库做的,但它也适用于 androidx):

    <?xml version="1.0" encoding="utf-8"?>
    <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">
    
    
    <Button
        android:id="@+id/button3"
        android:layout_width="0dp"
        app:layout_constraintWidth_percent="0.1"
        android:layout_height="wrap_content"
        android:text="<"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    
    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:text="TextView"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="@+id/button3"
        app:layout_constraintEnd_toStartOf="@+id/button4"
        app:layout_constraintStart_toEndOf="@+id/button3"
        app:layout_constraintTop_toTopOf="@+id/button3" />
    
    <Button
        android:id="@+id/button4"
        android:layout_width="0dp"
        app:layout_constraintWidth_percent="0.1"
        android:layout_height="0dp"
        android:text="x"
        app:layout_constraintBottom_toBottomOf="@+id/button3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@+id/button3" />
    
    </android.support.constraint.ConstraintLayout>
    

    它看起来像这样:

    现在您的 2 个按钮正好占据屏幕宽度的 10%,您可以告诉文本视图展开并占据剩余宽度 (android:layout_width="0dp")。

    但是如果我的文本非常大呢?

    在这种情况下,如果您想保持布局响应,您可以使用 [ssp(https://github.com/intuit/ssp) 库。

    一个 android SDK,它提供了一个新的尺寸单位 - ssp(可扩展的 sp)。此尺寸单位根据 sp 尺寸单位(用于文本)随屏幕尺寸缩放。它可以帮助 Android 开发者支持多屏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      • 2013-08-11
      • 2017-07-18
      相关资源
      最近更新 更多