How can I prevent views from overlapping in relative layout?
Best Fix:
android:layout_toStartOf="@id/item_on_the_right"
Could you instead contain those two TextViews within a horizontal LinearLayout (which itself would still be a child of your RelativeLayout). Then, assign appropriate weight attributes to each of the two TextViews within that LinearLayout.
To get same result using RelativeLayout
please use android:layout_toLeftOf="@+id/right_text"
. It will position the right edge of this view to the left of the given anchor view ID.
Please follow this example:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="@dimen/margin_material_small"
android:paddingRight="@dimen/margin_material_small">
<TextView
android:id="@+id/long_text"
style="@style/Base.TextAppearance.AppCompat.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/right_text"
android:singleLine="true"
tools:text="Some text field that will definitely overlap with another one" />
<TextView
android:id="@+id/right_text"
style="@style/Base.TextAppearance.AppCompat.Display1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:singleLine="true"
tools:text="10.34" />
<TextView
android:id="@+id/subtext"
style="@style/Base.TextAppearance.AppCompat.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/long_text"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/right_text"
android:singleLine="true"
tools:text="Some other text slightly smaller"/>
</RelativeLayout>
Result of above layout: