如何在约束布局 1.0 中使视图居中

Posted

技术标签:

【中文标题】如何在约束布局 1.0 中使视图居中【英文标题】:how to center a view in a constraint layout 1.0 【发布时间】:2019-08-28 06:42:49 【问题描述】:

我在约束布局中有一个视图(FrameLayout)

对于平板设备(仅限)我想要这个配置

1) its max height to say 100dp 

2) It has to be wrap content 

3) It has to be centered in its parent (vertically and
horizontally).

我有义务使用约束布局版本 1.0

我尝试将 Top-Bottom 用于其父约束,但它与其父约束的顶部对齐。

我尝试更改 app:layout_constraintHeight_default="wrap",但将其设置为 app:layout_constraintHeight_default="spread"` 违反了包装内容要求。

这是我的非平板电脑布局,我了解我想要制作平板电脑的所有内容,只有我会放在 values-sw600dp 资源文件夹下。

<?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_
    android:layout_
    android:background="@color/popup_view_scrim_color"
    android:fitsSystemWindows="true"
    tools:ignore="Overdraw">

  <FrameLayout
      android:id="@+id/viewToCenter"
      android:layout_
      android:layout_
      android:layout_marginTop="@dimen/account_menu_popover_top_margin"
      android:layout_marginBottom="@dimen/account_menu_popover_bottom_margin"
      android:layout_marginLeft="@dimen/account_menu_popover_side_margin"
      android:layout_marginRight="@dimen/account_menu_popover_side_margin"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintHeight_default="wrap"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintVertical_bias="0">
  </FrameLayout>
</android.support.constraint.ConstraintLayout>

我该如何解决这个问题?

【问题讨论】:

为什么是你的height==0dpConstraintLayout 中的 0dp 表示“匹配约束”。您是否尝试过使用android:layout_width="wrap_content" 【参考方案1】:

由于您希望视图居中,因此不需要所有这些边距:

<FrameLayout
    android:id="@+id/viewToCenter"
    android:layout_
    android:layout_
    app:layout_constraintHeight_default="wrap"
    app:layout_constraintWidth_default="wrap"
    app:layout_constraintHeight_max="100dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
</FrameLayout>

我添加了这些属性:

app:layout_constraintHeight_default="wrap"
app:layout_constraintWidth_default="wrap"

改成:

android:layout_

【讨论】:

以上是关于如何在约束布局 1.0 中使视图居中的主要内容,如果未能解决你的问题,请参考以下文章

自动布局视图 xib - 没有可编辑的约束?我需要居中的元素

一个iOS约束布局的小技巧

一个iOS约束布局的小技巧

在 IOS 中使用自动布局在邻居之间居中视图

在水平堆栈视图(自动布局)中将文本与图像垂直居中 - iOS

如何使用编程约束堆叠+居中两个文本视图?