Stephen McCormick
Stephen McCormick

Reputation: 1796

Android fitting image to only needed space

I have an image I want to display with text above it and a line below. I want the image to use the width of the space provided, then the height just enough to not waste space. The current XML setting is:

<LinearLayout 
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="normal"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="" />
     <ImageView 
        android:id="@+id/photoStatic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding ="5dp"
        android:layout_gravity="center"
        android:layout_weight="0"/>
    <View
        android:layout_marginTop="8dp"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/grey" />

</LinearLayout>

Here is what it ends up looking like:

enter image description here

I want to eliminate the empty space below the image and above it, so it sizes the image perfectly. I have tried modifying the android:layout_height and android:layout_width without much success.

Upvotes: 1

Views: 37

Answers (2)

Micer
Micer

Reputation: 8979

Attribute android:adjustViewBounds="true" should do the thing. Try this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="spam spam spam"
        android:textSize="18sp"
        android:textStyle="normal" />

    <ImageView
        android:id="@+id/photoStatic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="8dp"
        android:background="@color/grey" />

</LinearLayout>

Upvotes: 1

Efe AYDIN
Efe AYDIN

Reputation: 203

Just delete layout_weight. It is enough I think and also use Space instead of View (android.support.v4.widget.Space). Still using fill_parent? The same name is match_parent. fill_parent isn't used anymore.

Upvotes: 0

Related Questions