Reputation: 4408
I have a layout that has two components, a background image and an "icon" image, the icon is supposed to display an imageview at the center of the layout and the background takes up the full screen. when I set the height and width to 0dp of the icon to optimize the layout then manually set the height/width in code the image will show but in the top left of the layout. Almost like it's ignoring the center in parent attribute
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/ivBackground"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
<TextView
android:id="@+id/tvUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/ivIcon"
android:layout_centerHorizontal="true"
android:fontFamily="sans-serif-light"
android:shadowColor="#b3000000"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="3"
android:textAllCaps="false"
android:textColor="@color/white"
android:textSize="25sp" />
<ImageView
android:id="@+id/ivIcon"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_centerInParent="true"
android:adjustViewBounds="true" />
</RelativeLayout>
This layout is from a listview item, so later on once i've done some measurements I'll set the height/width
viewHolder.ivIcon.setLayoutParams(new RelativeLayout.LayoutParams(iconWidth, iconWidth));
So the image shows but in the top left, I feel like I'm missing something obvious
Upvotes: 1
Views: 685
Reputation: 434
I think whats probably happening is when you are setting the layout params you are overwriting the previous one which said center in parent. You should try this:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(iconWidth, iconWidth);
params.addRule(RelativeLayout.LayoutParams.CENTER_IN_PARENT);
viewHolder.ivIcon.setLayoutParams(params);
Upvotes: 1