Is it advisable to use LinearLayout inside ConstraintLayout in Android?
Is it advisable to use LinearLayout inside ConstraintLayout?
No... usually.
In general, the idea behind ConstraintLayout
is that it allows you to position all of your children without having to nest any other ViewGroup
s inside the ConstraintLayout
. As such, I would say that it is not advisable.
However, there are some things that a LinearLayout
can do that a ConstraintLayout
can't (mostly revolving around weighted spacing of views), and so if you need these particular corner cases in your layout, you won't have any option other than falling back to a LinearLayout
.
how popular is the ConstraintLayout among the developers?
ConstraintLayout
is relatively new, but it is quite powerful and certainly something that you ought to familiarize yourself with. It won't always be the perfect tool for the job at hand, but it will often allow you to easily create layouts you would otherwise spend hours on.
I can't speak to widespread adoption statistics, but I can say that I've seen tons of questions on this site about the correct usage of ConstraintLayout
, so clearly devs around the world are starting to work with it.
As of the 2.0.0-alpha5
release of the constraintlayout
library, it's now possible to declare a Flow virtual layout element within your ConstraintLayout which (as the name suggests) determines how referenced items are to flow (e.g. vertically, horizontally) within the ConstraintLayout. So it's no longer necessary to declare a LinearLayout within your ConstraintLayout.
For example, if you wanted items within your ConstraintLayout to flow vertically, you'd do so like this:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="I am the first TextView" />
<TextView
android:id="@+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="I am the second TextView" />
<TextView
android:id="@+id/textView3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="I am the third TextView" />
<androidx.constraintlayout.helper.widget.Flow
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="vertical"
app:constraint_referenced_ids="textView1,textView2,textView3"
app:flow_horizontalAlign="start"
app:flow_verticalGap="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
You can play around with the app:flow_
attributes in the Flow element to achieve different flow behaviour. For more information about the Flow element, refer to the release notes here. For an example, see here.