4

In case I have 2 views and I want one to take the necessary space and the other to take the remaining space, how should I go about it?

Let's suppose I want to lay the views vertically. The view below should take the necessary space (wrap_content) and the view above should take the remaining space of the container layout.

I've used these 2 solutions (simplified code):

1) LinearLayout with weight

<LinearLayout ...>
  <View height="0dp" weight="1" .../>
  <View height="wrap_content" .../>
</LinearLayout>

2) RelativeLayout with aligning

<RelativeLayout ...>
  <View height="wrap_content"    id="@+id/big" alignParentTop .../>
  <View height="wrap_content" below="@+id/big" alignParentBottom .../>
</RelativeLayout>

TheLinearLayout approach always work, and the RelativeLayout usually works as expected but it is obviously ambiguous, since nothing says that the @+id/big view should be bigger than the one below.

I think the first approach is better, since is not ambiguous. However, I have seen many examples and answers with the second approach.

What solution do you use for these cases. Is there a best practice?

Thanks!

EDIT

Taking Touf's answer, now I would do this (note the match_parent):

<RelativeLayout ...>
  <View height="match_parent"    id="@+id/big" alignParentTop .../>
  <View height="wrap_content" below="@+id/big" alignParentBottom .../>
</RelativeLayout>
Community
  • 1
  • 1
Ferran Maylinch
  • 10,919
  • 16
  • 85
  • 100

1 Answers1

7

I would use relative layout:

<View height="match_parent"    id="@+id/big" android:layout_above="@+id/view2" alignParentTop ... >

<View height="wrap_content" id="@+id/view2" alignParentBottom ...>

This way the first view will fill the screen height until it hits the 2nd view.

Touf
  • 106
  • 1
  • 6
  • Thanks, makes sense, although I don't know why android changed "fill_parent" to "match_parent". I mean, your solution would be quite clear with the old size qualifier: "fill the parent as much as you can". The new size seems to say "match the parent size". – Ferran Maylinch Nov 18 '15 at 00:36
  • 1
    "fill_parent" and "match_parent" are the same. Check out these links: http://stackoverflow.com/questions/10854717/why-did-match-parent-replace-fill-parent http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html – Touf Nov 18 '15 at 00:48
  • By the way, I guess I only need to use "above" or "below"; using both is redundant, isn't it? Maybe I should use below to reference the view that was declared before although I'm not sure whether I can use forward references (referencing views declared afterwards in the xml). – Ferran Maylinch Nov 18 '15 at 09:37
  • Yes I'm sorry no need for below="@+id/big", it is redundant, I forgot to remove it. – Touf Nov 18 '15 at 10:34
  • But how to set minHeight for firstview. I tried minHeight attribute but not working. The second view filled the screen completely (if its height is too large). – Jyoti JK Nov 01 '18 at 05:56