What can I use instead of LinearLayout in Android Jetpack Compose? An example of how common LinearLayout features might be replaced by the new API would be nice to have.
1 Answers
LinearLayout corresponds to Row and Column composables in Compose.
If you're going to display a large number of items take a look at LazyRow and LazyColumn which display only visible items like RecyclerView does but you can use these as simple as Row and Column. See What is the Jetpack Compose equivalent of RecyclerView or ListView? for an example.
Let's compare LinearLayout API to Row and Column:
android:orientation (LinearLayout)
As you might guessed <LinearLayout android:orientation="vertical" ...>
is equivalent to Column {}
and <LinearLayout android:orientation="horizontal" ...>
to Row {}
android:gravity (LinearLayout)
There're horizontalAlignment
& verticalArrangement
arguments for Column and verticalAlignment
& horizontalArrangement
for Row. For example:
<LinearLayout ...
android:orientation="vertical"
android:gravity="end|center">
...
</LinearLayout>
is equivalent to
Column(
...
horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.Center
) { ... }
android:layout_gravity (LinearLayout.LayoutParams)
See Row's align and Column's align modifiers which override the container alignment if it's set. There're also more advanced modifiers like Row's alignByBaseline, see the documentation for more details. For example:
<LinearLayout ...
android:orientation="vertical"
android:gravity="end">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="first" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="start"
android:text="second" />
</LinearLayout>
is equal to
Column(
...
horizontalAlignment = Alignment.End,
) {
// this item is aligned to the end according to the column's alignment
Text("first")
// but this one is aligned to the start because it overrides the alignment
Text("second", modifier = Modifier.align(Alignment.Start))
}
android:layout_weight (LinearLayout.LayoutParams)
See Row's weight and Column's weight modifiers. For example
<LinearLayout android:orientation="horizontal" ...>
<TextView
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:text="first" />
<TextView
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="2"
android:text="second" />
</LinearLayout>
is equal to
Row {
Text("first", modifier = Modifier.weight(1.0f))
Text("second", modifier = Modifier.weight(2.0f))
}

- 33,616
- 20
- 100
- 123