Question

I'm having trouble getting an ImageView that has been scaled down to center in my application. I've tried different scaleTypes (fitCenter, centerInside both give the correct dimensions but neither is centered), I've tried using RelativeLayout instead of LinearLayout, I've tried adding empty Views with a weight of 0.25 to either side, I've tried setting layout_width to a specific width rather than using layout_weight...nothing appears to do the trick, the image is just left aligned. Thoughts?

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:weightSum="1">
    <ImageView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:layout_gravity="center"
        android:src="@drawable/logo"
        android:adjustViewBounds="true"
        android:scaleType="centerInside" />
</LinearLayout>
Was it helpful?

Solution

The weighting is causing your problem here. You're specifying weightSum="1" on your LinearLayout, and then layout_weight="0.5" on your ImageView. This means that the image will only ever take up half the available space - the first half, for the layout you've got here. If you had set weightSum="2" and your image to layout_weight="0.5", your image would only take up one quarter of the space (since the assigned weight is 1/4 of the total).

You can fix this by either removing the weightSum and layout_weight attributes, or removing the LinearLayout altogether. I'd recommend removing the LinearLayout as there's no other children and it's not necessary;

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/logo"
    android:scaleType="centerInside" />

I misunderstood. This works for me:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="horizontal"
    android:weightSum="1">

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="0.25" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:adjustViewBounds="true"
        android:scaleType="centerInside"
        android:src="@drawable/logo" />

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="0.25" />

</LinearLayout>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top