Search code examples
javaandroidandroid-layoutandroid-imageviewandroid-image

How can I correctly put an image at the top of an ImageView having a specified height?


I am absolutly a beginner in Android development and I have some problem positioning an image into an ImageView element of my layout. So I have the following situation, I have this fragment layout:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Dummy content. -->
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="0dp">

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:scaleType="fitCenter"
            android:layout_height="350dp"
            android:src="@drawable/carbonara"/>
            <!--android:background="@drawable/carbonara" />-->

        <TextView android:id="@android:id/text1"
            style="?android:textAppearanceLarge"
            android:textStyle="bold"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp" />

    </LinearLayout>

</ScrollView>

So, as you can see in the previous code snippet I am setting a background image into an ImageView having an height of 350dp setted.

The problem is that the image height is less that 350dp and this is what I am obtaining:

enter image description here

As you can see in the previous screenshot what I obtain is that I have the 350dp ImageView (highlighted in blue) and the image is setted inside it vertically centered. I don't want that the setted image is vertically centerd but I want that it start at the top of the ImageView.

How can I implement this behavior? What am I missing?

I have tryed to change:

android:src="@drawable/carbonara"/>

with:

android:background="@drawable/carbonara" />

and in this way it fills all the ImageView space but in this way the image could appear deformed so I think that it is not a good solution.


Solution

  • try to change in your layout and test again.

    android:scaleType="fitCenter"
    

    to

    android:scaleType="fitStart"
    

    See full docs here