Reputation: 47
I have an imageview in Linearlayout I want its width to be fill_parent. I want its height to be whatever the width ends up being. For example:
<LinearLayout 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="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"
android:scaleType="centerCrop"
android:layout_margin="2dp"
tools:ignore="Suspicious0dp" />
</LinearLayout>
But it doesn't show the images in the android layout.. If I force change height of the imageview to 100dp in the code, it works, but I wonder why the height of image doesn't match to width even I wrote constraintDimensionRatio 1:1..
Thank you
Upvotes: 1
Views: 2189
Reputation: 6426
Try adding weight
to your imageview
then you will get the height
, otherwise you have to user wrap_content
as height
.
<LinearLayout 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="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scaleType="centerCrop"
android:layout_margin="2dp"
tools:ignore="Suspicious0dp" />
</LinearLayout>
<!--or if you don't want to use weight then user height = "wrap_content"-->
Upvotes: 1
Reputation: 853
You need to use ConstraintLayout as parent and set the dimension you want to make primary and another one to 0dp
. app:layout_constraintDimensionRatio="H,1:1"
means change height and make it 1:1 with width.
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="H,1:1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Upvotes: 2