kotlin 准备在不同屏幕中多次重复使用的按钮

b5lpy0ml  于 2022-11-25  发布在  Kotlin
关注(0)|答案(1)|浏览(116)

我有一个可重用的布局,包含一个LazyColumn和一个滚动到LazyColumn顶部的按钮。声明按钮(并确保click事件有效)的最有效方法是什么,这样我就不必在每次创建新屏幕时都对其进行decaler?

@Composable
fun MyReusableScaffold(scaffoldTitle: String, scaffoldContent: @Composable () -> Unit) {
    val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()

    Scaffold(
        modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
        topBar = {
            LargeTopAppBar(
                title = { Text(text = scaffoldTitle) },
                scrollBehavior = scrollBehavior
            )
        },
        content = { contentPadding ->
            scaffoldContent(contentPadding = contentPadding)
        }
    )
}

@Composable
fun MyScreen(navController: NavController) {
    MyReusableScaffold(
        scaffoldTitle = "Hello Android",
        scaffoldContent = {
            MyScreenContent(contentPadding = it)
        }
    )
}

@Composable
fun MyScreenContent(modifier: Modifier = Modifier,
    contentPadding: PaddingValues = PaddingValues()) {
LazyColumn(
state = listState,
contentPadding = contentPadding,
    ) {
        items(22) {
            ListItem(it)
        }
    }

val showButton by remember {
    derivedStateOf {
        listState.firstVisibleItemIndex > 0
    }
}

AnimatedVisibility(
    visible = showButton,
    enter = fadeIn(),
    exit = fadeOut(),
    modifier = Modifier.align(BottomCenter)
) {
    ScrollToTopButton(onClick = {
        coroutineScope.launch {
            listState.animateScrollToItem(index = 0)
        }
    })
}
}

@Composable
fun ScrollToTopButton(onClick: () -> Unit) {
    Box(
        Modifier
            .fillMaxSize()
    ) {
        Button(
            onClick = { onClick() }
        ) {
            Text(text = stringResource(id = R.string.top))
        }
    }
}
tkqqtvp1

tkqqtvp11#

您可以移动ScrollToTopButton内部的所有逻辑。
类似于:

@Composable
fun ScrollToTopButton(
    modifier : Modifier = Modifier,
    listState : LazyListState) {

    val coroutineScope = rememberCoroutineScope()

    val showButton by remember {
        derivedStateOf {
            listState.firstVisibleItemIndex > 0
        }
    }

    AnimatedVisibility(
        visible = showButton,
        enter = fadeIn(),
        exit = fadeOut(),
    ) {

        Box(
            modifier
        ) {
            Button(
                onClick = {
                    coroutineScope.launch {
                        listState.animateScrollToItem(index = 0)
                    }
                }

            ) {
                Text(text = "Top")
            }
        }
    }
}

然后在所有屏幕中使用:

val listState = rememberLazyListState()

LazyColumn(
    state = listState,
    contentPadding = contentPadding,
) {
    items(100) {
        androidx.compose.material.Text("" + it)
    }
}

ScrollToTopButton(
    listState = listState
)

相关问题