Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center fixed-size ImageView horizontally in parent ConstraintLayout

I have a rather simple layout: A ConstraintLayout filling the entire screen, with one big CardView that, at the top, has an ImageView that is half on the CardView and half above it (actually not half, but you get the point).

However, there are two issues: the ImageView sticks to the left of the parent and I do not know how to make it horizontally centered - all I can find on Google are chains for multiple elements, but I just want one centered.

The layout editor works extremely bad for me. My first complaint is that I seem to be unable to create constraints to the parent. Then I tried centering the ImageView horizontally in parent by pressing the button that says "Center in parent". This increases the CardView's width, no effect at all on the ImageView.

While I am at it, how could I z-order the ImageView on top of the CardView?

Here the layout:

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark">
<android.support.v7.widget.CardView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="32dp"
    android:layout_marginEnd="32dp"
    android:layout_marginStart="32dp"
    android:layout_marginTop="160dp"
    app:cardCornerRadius="12dp"
    app:cardElevation="32dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent">

</android.support.v7.widget.CardView>

<ImageView
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_marginTop="40dp"
    android:scaleType="centerCrop"
    android:src="@drawable/re_zero"

    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

Thanks!

like image 867
Zackline Avatar asked Jan 26 '17 21:01

Zackline


1 Answers

According to docs:

When you add a constraint to both sides of a view (and the view size for the same dimension is either "fixed" or "wrap content"), the view becomes centered between the two anchor points by default.

Adding the following constraint centered the ImageView.

app:layout_constraintEnd_toEndOf="parent"

Also, adding a higher elevation than the CardView fixed the z-index, since the elevation overrides z-index.

like image 159
Zackline Avatar answered Sep 30 '22 06:09

Zackline