Compose中是否有稳定版Bottom Sheet?生产环境如何替代实验性组件?
解决Compose中Bottom Sheet实验性组件的生产环境替代方案
用传统View体系的BottomSheetDialogFragment搭配Compose
既然官方Compose的Bottom Sheet组件还在实验阶段,直接复用Android View系统里已经稳定多年的BottomSheetDialogFragment,在里面嵌入Compose内容就行,完全不用担心稳定性问题。示例代码:class ComposeBottomSheet : BottomSheetDialogFragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return ComposeView(requireContext()).apply { setContent { // 这里写你的Bottom Sheet UI逻辑 Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 20.dp) ) { Text("这是Bottom Sheet内容", fontSize = 18.sp) // 其他按钮、列表等组件都可以正常写 } } } } }在Compose里调用也很简单:
val context = LocalContext.current Button(onClick = { ComposeBottomSheet().show( (context as AppCompatActivity).supportFragmentManager, "bottom_sheet_tag" ) }) { Text("弹出Bottom Sheet") }自己写一个Compose版的Bottom Sheet
基于Compose的稳定API完全可以自定义实现Bottom Sheet,核心就是用Draggable做拖拽、AnimatedVisibility做显示隐藏动画,完全避开实验性组件。比如:@Composable fun CustomBottomSheet( show: Boolean, onClose: () -> Unit, content: @Composable () -> Unit ) { if (show) { // 半透明背景,点击关闭 Box( modifier = Modifier .fillMaxSize() .background(Color.Black.copy(alpha = 0.5f)) .clickable { onClose() } ) { Column( modifier = Modifier .align(Alignment.BottomCenter) .fillMaxWidth() .background(Color.White) // 处理拖拽关闭逻辑 .draggable( orientation = Orientation.Vertical, state = rememberDraggableState { delta -> if (delta > 100) onClose() } ) ) { // 顶部的拖拽指示器 Box( modifier = Modifier .align(Alignment.CenterHorizontally) .padding(top = 8.dp) .size(40.dp, 4.dp) .background(Color.Gray.copy(alpha = 0.5f)) .clip(RoundedCornerShape(2.dp)) ) // 自定义内容 content() } } } }这种方式完全可控,想加什么动画、逻辑都自己说了算,而且全用稳定API,生产环境放心用。
等官方稳定版发布
如果项目排期不紧张,可以先用临时UI占位,等Google把官方Bottom Sheet组件从实验版转正。Compose的迭代速度不慢,实验性组件通常几个版本后就会稳定,关注官方版本更新日志就行。选第三方稳定库
找一些已经经过生产验证的第三方Compose Bottom Sheet库,这些库一般都是基于稳定Compose API封装的,避开了官方实验组件的坑。不过选的时候要注意看库的维护状态,别选没人维护的冷门库。
内容的提问来源于stack exchange,提问作者Emy Abobakr
相关产品推荐
相关产品推荐

