我参照官方示例,在class MainActivity的override fun onCreate函数中,成功运行起了Snackbar,代码如下:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
setContent {
AliyouyuTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) },
floatingActionButton = {
var clickCount by remember { mutableStateOf(0) }
ExtendedFloatingActionButton(
onClick = {
// show snackbar as a suspend function
scope.launch {
snackbarHostState.showSnackbar(
"Snackbar # ${++clickCount}"
)
}
}
) { Text("Show snackbar") }
},
content = { innerPadding ->
Text(
text = "Body content",
modifier = Modifier
.padding(innerPadding)
.fillMaxSize()
.wrapContentSize()
)
}
)
}
}
}
}
}
但我分离业务代码到独立的函数中时,却无论如何都无法show一个snackbar:
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginForm(
modifier: Modifier = Modifier,
) {
val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
Scaffold(
modifier = modifier,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier,
) {
Text(
text = "title",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),
textAlign = TextAlign.Center,
modifier = Modifier.padding(top = 64.dp, bottom = 12.dp)
)
Button(
onClick = {
scope.launch {
Log.d("scope.launch", "测试")
snackbarHostState.showSnackbar(
message = "Snackbar",
actionLabel = "Action",
)
}
},
modifier = Modifier
.fillMaxWidth()
.padding(top = 28.dp, bottom = 3.dp)
) {
Text(
text = "登录",
style = MaterialTheme.typography.titleSmall
)
}
}
}
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AliyouyuTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
LoginScreen()
}
}
}
}
}
已经用google搜了大半天了,依然没有任何头绪,还忘高手解答。