Home > front end >  Jetpack compose scrollable table
Jetpack compose scrollable table

Time:05-08

I need to have a component that scrolls vertically and horizontally.

Here is what I did so far:

@Composable
fun Screen() {
    val scope = rememberCoroutineScope()
    val scrollOffset = remember {
        mutableStateOf(value = 0F)
    }
    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.spacedBy(space = 16.dp)
    ) {
        items(10) {
            SimpleRow(
                onScrollOffsetChange = {
                    scrollOffset.value = it
                }
            )
        }
    }
}

@Composable
private fun SimpleRow(
    onScrollOffsetChange: (Float) -> Unit,
) {
    val lazyRowState = rememberLazyListState()
    LazyRow(
        modifier = Modifier.fillMaxWidth(),
        state = lazyRowState
    ) {
        item {
            Text(
                text = "firstText"
            )
        }
        for (i in 1..30) {
            item {
                Text(text = "qwerty")
            }
        }
    }
}

When anyone of these SimpleRow is scrolled I want to scroll all of the SimpleRows together.

And I do not know how many SimpleRows I have because they came from our server.

Is there any kind of composable or trick that can do it for me?

CodePudding user response:

You can use multiple rows inside a column that scrolls horizontally and vertically, like this:

@Composable
fun MainContent() {
    val scrollStateHorizontal = rememberScrollState()
    val scrollStateVertical = rememberScrollState()

  Column(
      modifier = Modifier
          .fillMaxSize()
          .verticalScroll(state = scrollStateVertical)
          .horizontalScroll(state = scrollStateHorizontal)
  ) {
      
      repeat(40){ c ->
          Row {
              repeat(40){ r ->
                  Item("col: $c | row: $r")
              }
          }
      }
      
  }
}

@Composable
fun Item(text: String) {
    Text(
        modifier = Modifier
            .padding(5.dp)
            .background(Color.Gray),
        text = text,
        color = Color.White
    )
}

sample image

  • Related