I have a parent LinearLayout
with an ImageView
and a child LinearLayout
inside. The LinearLayout
child has text inside it that can have different lengths. I would like that the ImageView
was always of the same size (200dpx200dp) and only scaled down proportionally it if the text of the child LinearLayout overflow.
To do that I have used layout_weight
and maxHeight
in the ImageView child, but due to the layout_weight, maxHeight is not working. The ImageView
is not squared when the text of the child LinearLayout
doesn't overflow, instead is displayed rectangular.
How could I do it?
This is the code
<ImageView
android:id="@+id/charImage"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_width="wrap_content"
android:maxWidth="200dp"
android:maxHeight="200dp"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="@drawable/jon_snow" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="vertical">
----some childs----
</LinearLayout>
This is how it should like, a square ImageView with some text underneath, independently of the length of the text.
I have tried to modify onMeasure() of custom ImageView, but it's not resizing properly and it's taking some of the space of the LinearLayout child and the text overflows
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int height = Math.min(widthMeasureSpec, Math.min(heightMeasureSpec, dpToPx(200)));
setMeasuredDimension(height, height);
}
private int dpToPx(int dp){
float density = getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}