Is there a way to tell a `Row` to invert the order...
# compose
j
Is there a way to tell a
Row
to invert the order it lays out its content? (e.g. LTR instead of RTL)
1
z
You mean other than actually just changing the layout direction, I presume? (Not actually sure if doing so would even have that effect, but I would think)
j
yes, but it has to be “local” somehow, i.e it shouldn’t affect other composables
I mean… changing the
LayoutDirection
would be great, but can it be done for that
Row
only?
z
Change it back before adding the actual row children? Not very elegant, admittedly, but probably easier than reimplementing Row from scratch
j
Sounds like I suck at explaining… lemme show an example
with boolean param: false ||A|B|……|| with boolean param: true ||……|B|A|| (|| are the screen boundaries, the dots are just empty sapce)
z
eg
Copy code
val originalDirection = LocalLayoutDirection.current
val flippedDirection = if (originalDirection == Ltr) Rtl else Ltr
CompositionLocalProvider(LocalLayoutDirection provides flippedDirection) {
  Row(…) {
    CompositionLocalProvider(LocalLayoutDirection provides originalDirection) {
      // Row children here
    }
  }
}
j
oh super, sounds like a great place to start!
z
of course you could factor that all out into a custom
Row
if you needed to reuse it lots
j
Thanks a bunch, leaving this here for whoever might come by:
Copy code
@Composable
fun InvertibleRow(
  isInverted: Boolean,
  modifier: Modifier = Modifier,
  horizontalArrangement: Arrangement.Horizontal = Arrangement.Start,
  verticalAlignment: Alignment.Vertical = <http://Alignment.Top|Alignment.Top>,
  content: @Composable RowScope.() -> Unit
) {
  val layoutDirection: LayoutDirection = LocalLayoutDirection.current
  CompositionLocalProvider(
    LocalLayoutDirection provides if (isInverted) layoutDirection.invert() else layoutDirection
  ) {
    Row(
      modifier = modifier,
      horizontalArrangement = horizontalArrangement,
      verticalAlignment = verticalAlignment
    ) {
      CompositionLocalProvider(LocalLayoutDirection provides layoutDirection) {
        content()
      }
    }
  }
}

private fun LayoutDirection.invert(): LayoutDirection = when (this) {
  LayoutDirection.Ltr -> LayoutDirection.Rtl
  LayoutDirection.Rtl -> LayoutDirection.Ltr
}
👍 1
c
A much easier way is to use
LazyRow
and
reverseLayout
. This honors the layout direction:
LazyRow(reverseLayout = true)
😮 4