Android Studio
代码解释
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GreetingCardTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Greeting("Android")
}
}
}
}
}
onCreate()
函数时此应用的入口点,并会调用其他函数来构建UI。在Android应用中由onCreate()
函数替代了main()
在Kotlin程序中的作用.
onCreate()
函数中的setContent()
函数用于通过可组合函数定义布局.
任何标有@Composable
注解的函数都可通过setContent()
函数或其他可组合函数进行调用.
Greating()
函数是一种可组合函数,他会接受一些输入并生成屏幕上显示的内容。
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
GreetingCardTheme {
Greeting("Meghan")
}
}
若想要使其成为预览函数,需要添加@Preview
注解,showBackground
参数可以用于添加背景
使用方法
更改背景颜色
若要为自我介绍设置不同的背景颜色,需要使用Surface
将文本包围起来.Surface
是一个容器,代表界面的一部分
- 按下
Alt+Enter
(Windows),选择Surround with widget。 - 选择Surround with Container
- 修改Box为你需要的容器
- 设置Surface的color参数
- 在顶部引入相应的color包androidx.compose.ui.graphics.Color
添加内边距
- 映入相应的包
2.使用
Modifier.padding()
函数