Reputation: 412
I am trying to create a recycler view item to show multiple rows of multiple images side-by-side:
I want to avoid setting any width or height as I want the images to scale to fill the available width of the screen. I am trying to do this with purely Android layout XML (ie. would rather not do it programmatically if possible) and want to avoid setting a fixed height. However I cannot find any applicable height settings to achieve this.
The Stack Overflow topics always I find tend to suggest layout_weight
, which 'almost works' as the images do fill the available width, however the height of the wrapper is too big and it is still the height of the original images.
See in the image below, the blue line shows the height of the container, which gives the appearance of a lot of unintentional margin/padding.
Is it possible to amend the following to also trim the height of the wrapper to fit the images more accurately?
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/card_1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/card_ha" />
<ImageView
android:id="@+id/card_2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/card_ha" />
<ImageView
android:id="@+id/card_3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/card_ha" />
</LinearLayout>
</layout>
Upvotes: 0
Views: 802
Reputation: 6363
Have you tried adjustViewBounds
?
See, As per the official documentation and my usage experience as well, adJustViewBounds
does the job from xml to adjust the ImageView's
bounds/borders according to the ratio of the image/drawable as also mentioned in the image attached below.
So, if you set the width
to 0dp
and height
to wrap_content
which you've already done, ImageView's size will adjust as per the aspect ratio.
To do it: Add android:adjustViewBounds="true"
in the all of the ImageViews
tags. You don't have to do anything else programmatically or in xml.
Also, I would suggest using GridView
if you're thinking of adding more rows of images, otherwise no need.
Upvotes: 3