当我在代码中使用 CenterAlignedTopAppBar 时出现编译错误

问题描述 投票:0回答:2

嗨,我是 jetpack 的新手,这是我的代码

@Composable
fun WoofApp() {
    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(title = { Text(text = "hi") }) // ERROR
        }
    ) { it ->
        LazyColumn(contentPadding = it) {
            items(dogs) {
                DogItem(
                    dog = it,
                    modifier = Modifier.padding(dimensionResource(id = R.dimen.padding_small))
                )
            }
        }
    }
}

我在 android studio 中有 CompilationErrorException,它说

e:(错误上方)此材料 API 是实验性的,将来可能会更改或删除。

我尝试使用 TopAppBar() 而不是 CenterAlignedTopAppBar() 但仍然遇到相同的错误

kotlin android-jetpack-compose
2个回答
1
投票

我假设您正在使用 material 3 API,它仍然是 实验性,因此您必须在可组合函数上使用此

annotation
@OptIn(ExperimentalMaterial3Api::class)
所以你的函数应该是这样的:

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WoofApp() {
    Scaffold(
        topBar = {
            CenterAlignedTopAppBar(title = { Text(text = "hi") }) // ERROR
        }
    ) { it ->
        //some code
    }
}

0
投票

在所有函数之前,甚至在 MainActivity 类之前,您需要提及:

@ExperimentalMaterial3Api

像这样:

@ExperimentalMaterial3Api
@Composable
fun WoofTopAppBar(modifier: Modifier = Modifier) { ...

还有这个:

@ExperimentalMaterial3Api
class MainActivity : ComponentActivity() {  ...

然后导入

import androidx.compose.material3.ExperimentalMaterial3Api
© www.soinside.com 2019 - 2024. All rights reserved.