'Change layout direction of a Composable

I want to set a direction of a specific composable to be RTL


@Composable
fun ViewToBeChanged() {
  Row {
     Image()
     Column {
        Text("Title")
        Text("Subtitle")
    }
  }
}

Is it possible?

Jetpack compose Layout documentation mentions LocalLayoutDirection

Change the layout direction of a composable by changing the LocalLayoutDirection compositionLocal.

But I have no idea how to use it in a composable to take effect.



Solution 1:[1]

You can use the CompositionLocalProvider to provide a custom LocalLayoutDirection.

Something like:

CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl ) {
    Column(Modifier.fillMaxWidth()) {
        Text("Title")
        Text("Subtitle")
    }
}

Solution 2:[2]

Since I did not have your image, I tweaked your composable to:

@Composable
fun ViewToBeChanged() {
  Row {
    Text("Foo", modifier = Modifier.padding(end = 8.dp))

    Column {
      Text("Title")
      Text("Subtitle")
    }
  }
}

That gives us:

ViewToBeChanged() rendering

One way to switch to RTL is to use CompositionLocalProvider and LocalLayoutDirection:

@Composable
fun RtlView() {
  CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
    Row {
      Text("Foo", modifier = Modifier.padding(end = 8.dp))

      Column {
        Text("Title")
        Text("Subtitle")
      }
    }
  }
}

Here, we are saying that we are overriding the CompositionLocal for layout direction for the contents of the trailing lambda supplied to CompositionLocalProvider(). This gives us:

RtlView() rendering

This changes the layout direction used by this branch of the composable tree, for the composables itself. English is still a LTR language, so the text is unaffected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabriele Mariotti
Solution 2 CommonsWare