Make View fill space leftover in parent view using ConstraintLayout

Pius Aboyi
2 min readApr 25, 2019

--

Sometimes we want to design a layout that has one view or some set of views with specific height or width while the next view beside/below/above it should just fill whatever space that’s left. Good old LinearLayout has a way of letting one do this using layout_weight but for this post we will be learning how to get it done using ConstraintLayout.

The thing I lovethe most about how ConstraintLayout gets the job done is how obvious the code looks. Its so easy to relate it to simple laws of physics.

<android.support.v7.widget.RecyclerView
android:id="@+id/demo_recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/app_bar_layout"
/>
<android.support.design.widget.BottomNavigationView
android:id="@+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:background="?android:attr/windowBackground"
app:menu="@menu/navigation"
/>

In this example we have an activity that displays a List (RecyclerView) and a BottomNavigation widget. We want this list to fill whatever space that is left between the app_bar_layout and the BottomNavigationView. The code above shows how that is done by setting the height of the RecyclerView to 0dp. And also setting constraints for top (layout_constraintTop_toBottomOf) and bottom (layout_constraintBottom_toTopOf) of the RecyclerView to the AppBar and BottomNavigationBar respectively as shown in the code above.

The physics is like telling android to place the RecyclerView just below the AppBar and set the height to fill all space till top of BottomNavigationBar.

Here is a screenshot of the output:

ConstraintLayout bottom_nav example

With this pattern (and if you do not set any vertical margins) the list will scroll smoothly and no detail will be lost under the bottom navigation at the end of the list. Same applies to the app bar at the top of the list. There is so much you can do with ConstraintLayout but that’s all for this post. Cheers and Happy coding.

--

--

Pius Aboyi

Web/Mobile Developer(Android), I know PHP, SEO+Digital marketing. Currently growing the tech Eco-system in Benue, Nigeria, via BenueTechForum and GDG Makurdi.