BBNN
BBNN

Reputation: 33

Android - center of element (image) on top of another element

I want to create view where one element's vertical center (ImageView - black circle) is exactly on top/start of another element (LinearLayout - red box). In other words - half of black circle should be above red layout and half of it should be inside. What is the easiest way to do that? Is it possible to achieve in xml?

enter image description here

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/red"
        android:layout_alignParentBottom="true"
        android:layout_above="@+id/red_block">
           SOME OTHER VIEWS INSIDE
    </LinearLayout>
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/some_circle"
        android: CENTER_ON_TOP_OF_RED_BLOCK??? />
</RelativeLayout>

Upvotes: 0

Views: 42

Answers (1)

Kai
Kai

Reputation: 455

It's time to use ConstraintLayout.

You can let the vertical center of black circle align the top of red block by this two attribute

app:layout_constraintTop_toTopOf="@id/red_block" app:layout_constraintBottom_toTopOf="@id/red_block"

xml:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:id="@+id/red_block"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@android:color/red"
        android:orientation="vertical"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent">
        <!--SOME OTHER VIEWS INSIDE-->
    </LinearLayout>
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/some_circle"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@id/red_block"
        app:layout_constraintBottom_toTopOf="@id/red_block" /> 
</androidx.constraintlayout.widget.ConstraintLayout>

preview:

enter image description here

Upvotes: 1

Related Questions