androidandroid-layoutandroid-constraintlayoutxml-layout

Placing an image on the top left of another image using Constraint Layout


I'm trying to place an icon top left of an image using Constraint Layout but it needs to be offset from the center of its sides. Like in the pictures:

This is what I've got so far:

This is what I've got so far

This is the end goal:

This is the end goal

and this is my xml file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@color/grey_500">

    <ImageView
        android:id="@+id/iv_landscape_art"
        android:layout_width="240dp"
        android:layout_height="150dp"
        android:layout_marginTop="48dp"
        android:elevation="2dp"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"
        android:background="@android:color/white"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <ImageView
        android:id="@+id/iv_sold_icon"
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:adjustViewBounds="true"
        android:background="@color/colorPrimary"
        android:elevation="4dp"
        android:scaleType="fitXY"
        app:layout_constraintTop_toTopOf="@+id/iv_landscape_art"
        app:layout_constraintStart_toStartOf="@id/iv_landscape_art"
        app:layout_constraintEnd_toStartOf="@+id/iv_landscape_art"
        app:layout_constraintBottom_toTopOf="@+id/iv_landscape_art"/>

How do I accomplish that?


Solution

  • The simplest way to offset the smaller square from the top left corner of the larger square is to apply an X and Y translation. Add the following to the XML of the smaller square to see what I mean.

    android:translationX="10dp"
    android:translationY="10dp"
    

    Another way to offset the smaller square is to place a Space widget in the top left corner of the larger square and make the sides of the Space 48dp in length. Now constrain the right and bottom sides of the smaller square to the right and bottom sides of the Space widget.