Impossible put at the top one image using a constraintlayout in android

871 Views Asked by At

I'm trying to put an image header at the top of the constraintlayout but when i run the app in a real device it is wrong and the header is not in the top:

enter image description here


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/header"
        android:layout_width="0dp"
        android:layout_height="207dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_header" />
    
</androidx.constraintlayout.widget.ConstraintLayout>

below we can see how looks it in a real device:

enter image description here

There is a space between the action bar and the header. I tried to remove the action bar but also does not work. Thanks in advance.

This is my content of ic_header:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="360dp"
    android:height="180dp"
    android:viewportWidth="360"
    android:viewportHeight="180">
  <path
      android:pathData="M0,0h360v180h-360z"
      android:fillColor="#fbc711"/>
</vector>
2

There are 2 best solutions below

2
Chirag Kalra On

I think the issue is with the src drawable and the ImageView both having a fixed height.

Try using android:scaleType="centerCrop" in your ImageView xml, so that the source image expands to cover the empty area.

2
Tejas Dhawale On

I tried running your code and found out that given constraints are right but your SVG isn't scaling to the total length for your ImageView. You can see the view bounds below

enter image description here

Solution: You can consider adding this line.

 android:scaleType="fitXY"

The result will be like the following image.

enter image description here

and the alternate solution is you can also use shape drawable if all you need is a solid layout.

And if you drawable isn't a solid color and some complex vector image. try not to resize your image view. keep

android:layout_height="wrap_content"