Search code examples
androidandroid-layoutandroid-relativelayout

Why RelativeLayout keeps messing its inner layout while its height is set to WRAP_CONTENT?


I have a RelativeLayout with which wraps around an ImageView and 2 TextViews. The problem here is when I set the height of it to wrap_content one of the TextViews overlaps the other while it's set to reside under it but I set the height to a specific dp (like 56dp) it's fine. Please refer to the code below.

<?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="wrap_content"
    android:background="?attr/selectableItemBackground"
    android:clickable="true"
    android:focusable="true">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/avatar"
        android:layout_width="36dp"
        android:layout_height="36dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_margin="10dp"
        android:scaleType="centerCrop"
        android:src="@drawable/new_profile_avatar"/>

    <com.imnumbers.newpkg.widget.CustomTextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/avatar"
        android:text="Hamed Momeni"/>

    <TextView
        android:id="@+id/number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:layout_toEndOf="@+id/avatar"
        android:layout_toRightOf="@+id/avatar"
        android:text="+989888898885"
        android:textSize="9sp"
        />

</RelativeLayout>

I have also included screenshots to illustrate the problem.

Screenshot of how it looks:
Wrong

Screenshot of how it should look:
Right


Solution

  • android:layout_centerVertical="true" for name, android:layout_below="@+id/name" for number and android:layout_height="wrap_content" for RelativeLayout created interdependency and result in error

    Suggested fixes:

    1. Remove android:layout_centerVertical="true" for name, you may add marginTop for name to move it down a bit, e.g. android:layout_marginTop="5dp"; or
    2. Set fixed height for RelativeLayout, i.e. android:layout_height="36dp"