Android Studio Jetpack Compose:实现上滑推页露出底部登录选项面板
实现Jetpack Compose欢迎页上滑露出底部登录面板
你要的堆叠式滑动效果可以通过Box布局+拖动手势+动画实现,核心思路是把登录面板放在底层,欢迎页叠在上方,通过拖动手势控制欢迎页的垂直偏移量,露出下方的登录面板,完全规避ModalBottomSheet的覆盖问题。
完整实现代码
import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectVerticalDragGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.dp @Composable fun WelcomeScreenWithSlidePanel() { // 登录面板高度,可按需调整 val panelHeight = 200.dp val panelHeightPx = panelHeight.value * density // 管理欢迎页垂直偏移量,初始值0表示完全覆盖面板 val offsetY = remember { Animatable(0f) } // 拖动阈值:超过面板高度的1/2时自动展开,否则回弹收起 val dragThreshold = panelHeightPx / 2 Box(modifier = Modifier.fillMaxSize()) { // 底层:登录选项面板 Column( modifier = Modifier .fillMaxWidth() .height(panelHeight) .align(androidx.compose.ui.Alignment.BottomCenter) .background(Color.LightGray) ) { Text(text = "登录选项") Button(onClick = { /* 账号密码登录逻辑 */ }) { Text(text = "账号密码登录") } Button(onClick = { /* 第三方登录逻辑 */ }) { Text(text = "微信登录") } } // 上层:欢迎页 Column( modifier = Modifier .fillMaxSize() .background(Color.White) .offset(y = offsetY.value) .pointerInput(Unit) { detectVerticalDragGestures( onDrag = { _, dragAmount -> // 实时更新偏移量,限制范围:0(收起)到 -panelHeightPx(完全展开) val newOffset = offsetY.value + dragAmount offsetY.snapTo(newOffset.coerceIn(-panelHeightPx, 0f)) }, onDragEnd = { // 拖动结束后触发展开/收起动画 val targetOffset = if (offsetY.value <= -dragThreshold) { -panelHeightPx } else { 0f } offsetY.animateTo(targetOffset, animationSpec = tween(300)) } ) } ) { Text(text = "欢迎页内容") // 此处添加欢迎页其他UI元素 } } }
关键逻辑说明
- 布局结构:用
Box实现堆叠效果,登录面板固定在底部,欢迎页占满屏幕叠在上方。 - 拖动手势控制:通过
detectVerticalDragGestures监听垂直拖动,实时调整欢迎页的offset值,同时限制偏移范围防止过度拖动。 - 平滑动画过渡:拖动结束后根据偏移量判断是否触发展开/收起,用
Animatable实现300ms的平滑动画,提升交互体验。 - 参数自定义:可根据需求调整
panelHeight(面板高度)、dragThreshold(触发阈值)、tween(300)(动画时长)等参数,适配自身UI设计。
内容的提问来源于stack exchange,提问作者Ege Karaca
相关产品推荐
相关产品推荐

