简体   繁体   中英

how to center a view in a constraint layout 1.0

I have a view (FrameLayout) in a constraintLayout

For tablet devices (only) I want to have this configuration

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

I'm obligated to use constraint layout version 1.0

I have tried to use Top-Bottom to its parent constraints, but it's aligned to its parent's top.

I have tried to change app:layout_constraintHeight_default="wrap" but making it app:layout_constraintHeight_default="spread"` violates the wrap content requirement.

Here is my non-tablet layout, and I understand everything I want to make tablet only I would put under the values-sw600dp resources folder.

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

  <FrameLayout
      android:id="@+id/viewToCenter"
      android:layout_width="300dp"
      android:layout_height="0dp"
      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>

How can i fix this?

在此输入图像描述

Since you want the view to be centered there is no need for all those margins:

<FrameLayout
    android:id="@+id/viewToCenter"
    android:layout_width="0dp"
    android:layout_height="0dp"
    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>

I added these attributes:

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

and changed to:

android:layout_width="0dp"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM