Issue with RelativeLayout when View visibility is View.GONE

I've a RelativeLayout thus:

<RelativeLayout>
<TextView1/>
<TextView2/> // <-- View.VISIBLE OR View.GONE
<TextView3/>
<TextView4/>
</RelativeLayout>

Each TextView is anchored below the previous TextView with android:layout_below.

The problem is that TextView2 may or may not be there (either View.VISIBLE or View.GONE); if it's View.VISIBLE, then all is fine, but if it's View.GONE, then TextView3 ends up being rendered on top of TextView1.

I've tried various ways to fix this, but each time am caught out by RelativeLayout's 'you cannot reference an id before it's defined' rule.

I'm hoping that I'm missing something obvious here.


You can use this tag:

android:layout_alignWithParentIfMissing="true"

From the docs:

If set to true, the parent will be used as the anchor when the anchor cannot be be found for layout_toLeftOf, layout_toRightOf, etc.


You can place textview 2 and 3 in the LinearLayout and keep the linear layout below textview 1.