以下是 Jetpack Compose 中常用的一些组件的列表:
组件名称 | 描述 |
---|---|
Text |
用于显示文本内容。 |
Button |
可点击的按钮组件,常用于触发事件。 |
TextField |
用于输入文本的文本框组件。 |
Image |
用于展示图片。 |
Column |
垂直布局容器,可以在其中垂直排列子组件。 |
Row |
水平布局容器,可以在其中水平排列子组件。 |
Box |
用于层叠布局,可以让子组件重叠。 |
LazyColumn |
用于显示可滚动的垂直列表,适用于展示大量数据。 |
LazyRow |
用于显示可滚动的水平列表,适用于展示大量数据。 |
Slider |
滑动条组件,可用于调整数值。 |
Switch |
开关组件,用于切换状态。 |
Checkbox |
复选框组件,用于表示选中或未选中状态。 |
RadioButton |
单选按钮组件,常用于一组选项中选择一个。 |
Card |
卡片组件,用于展示相关联的信息,如图文信息。 |
AlertDialog |
对话框组件,用于显示警告或提示信息,并可包含操作按钮。 |
Scaffold |
提供基本的 Material Design 布局结构,如顶部应用栏、底部导航、抽屉菜单等。 |
TopAppBar |
顶部应用栏组件,常用于提供导航和操作。 |
BottomNavigation |
底部导航栏组件,用于在不同页面间进行切换。 |
FloatingActionButton |
浮动操作按钮,常用于执行主要的应用操作。 |
Divider |
分割线组件,用于在视觉上分隔内容。 |
ProgressIndicator |
进度指示器组件,用于显示操作的进度。 |
Spacer |
用于添加空白间隔的组件,常用于调整布局间距。 |
演示:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!--Load images from Unsplash-->
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.Jetsnack">
<profileable android:shell="true" tools:targetApi="q" />
<activity
android:name="com.treevalue.jetsnack.MainActivity"
android:theme="@style/Theme.Jetsnack"
android:exported="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
import androidx.compose.foundation.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.material.Typography
@Composable
fun MyApplicationTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) {
darkColors(
primary = Color(0xFFBB86FC),
primaryVariant = Color(0xFF3700B3),
secondary = Color(0xFF03DAC6)
)
} else {
lightColors(
primary = Color(0xFF1EB980),
primaryVariant = Color(0xFF045D56),
secondary = Color(0xFF03DAC6)
)
}
MaterialTheme(
colors = colors,
typography = Typography(),
shapes = Shapes(),
content = content
)
}
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.graphics.*
import androidx.compose.ui.res.*
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.*
import androidx.compose.foundation.lazy.*
import com.example.jetsnack.R
@Composable
fun MyApp() {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Greeting(name = "Jetpack Compose")
Spacer(modifier = Modifier.height(16.dp))
MyButton()
Spacer(modifier = Modifier.height(16.dp))
MyTextField()
Spacer(modifier = Modifier.height(16.dp))
MyImage()
Spacer(modifier = Modifier.height(16.dp))
MyColumn()
Spacer(modifier = Modifier.height(16.dp))
MyRow()
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApp()
}
@Composable
fun MyTextField() {
var text by remember { mutableStateOf("") }
TextField(
value = text,
onValueChange = { newText -> text = newText },
label = { Text(text = "Enter something") }
)
}
@Composable
fun Greeting(name: String) {
Text(text = "Hello, $name!")
}
@Composable
fun MyButton() {
Button(onClick = { /* Do something */ }) {
Text(text = "Click Me")
}
}
@Composable
fun MyColumn() {
Column {
Text(text = "Item 1")
Text(text = "Item 2")
Text(text = "Item 3")
}
}
@Composable
fun MyRow() {
Row {
Text(text = "Item A")
Text(text = "Item B")
Text(text = "Item C")
}
}
@Composable
fun MyImage() {
Image(
painter = painterResource(id = R.drawable.lyy),
contentDescription = "My Image"
)
}
1. Column(垂直布局)
Column
用于在垂直方向上排列子组件。可以通过 verticalArrangement
和 horizontalAlignment
控制子组件的排列方式和对齐方式。
kotlin
@Composable
fun ColumnExample() {
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.SpaceBetween,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("First Item")
Text("Second Item")
Text("Third Item")
}
}
2. Row(水平布局)
Row
用于在水平方向上排列子组件。与 Column
类似,Row
也支持 horizontalArrangement
和 verticalAlignment
属性。
kotlin
@Composable
fun RowExample() {
Row(
modifier = Modifier.padding(16.dp),
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically
) {
Text("Left")
Text("Center")
Text("Right")
}
}
3. Box(层叠布局)
Box
允许子组件在层叠的形式中存在,可以用来创建重叠的UI效果。
kotlin
@Composable
fun BoxExample() {
Box(
modifier = Modifier
.size(150.dp)
.background(Color.LightGray),
contentAlignment = Alignment.Center
) {
Text("Bottom", modifier = Modifier.align(Alignment.BottomCenter))
Text("Top", modifier = Modifier.align(Alignment.TopCenter))
}
}
4. LazyColumn 和 LazyRow(滚动列表)
LazyColumn
和 LazyRow
类似于 RecyclerView,在展示大量数据时非常有用。
kotlin
@Composable
fun LazyColumnExample() {
LazyColumn {
items(100) { index ->
Text("Item $index", modifier = Modifier.padding(8.dp))
}
}
}
@Composable
fun LazyRowExample() {
LazyRow {
items(100) { index ->
Text("Item $index", modifier = Modifier.padding(8.dp))
}
}
}
5. Scaffold(结构布局)
Scaffold
提供了一个基本的 Material Design 布局结构。
kotlin
@Composable
fun ScaffoldExample() {
Scaffold(
topBar = { TopAppBar(title = { Text("Scaffold Example") }) },
floatingActionButtonPosition = FabPosition.End,
floatingActionButton = { FloatingActionButton(onClick = {}) { Icon(Icons.Filled.Add, contentDescription = "Add") } },
content = { innerPadding ->
Box(modifier = Modifier.padding(innerPadding)) {
Text("Content goes here")
}
}
)
}
Box
组件的基本用途是允许其子组件以层叠的方式显示。可以通过 modifier
属性控制 Box
的大小、填充、背景色等。
kotlin
@Composable
fun BasicBoxExample() {
Box(
modifier = Modifier
.size(200.dp)
.background(Color.Gray),
contentAlignment = Alignment.Center
) {
Text("Centered Text", style = TextStyle(color = Color.White))
}
}
子组件定位
在 Box
中,子组件可以通过 Modifier.align
定位到不同的位置。例如,可以将一个组件定位在底部中心,另一个定位在顶部中心。
kotlin
@Composable
fun PositionedBoxExample() {
Box(
modifier = Modifier
.size(200.dp)
.background(Color.LightGray)
) {
Text("Top Center", Modifier.align(Alignment.TopCenter))
Text("Bottom Center", Modifier.align(Alignment.BottomCenter))
}
}
使用层叠实现复杂界面
Box
可以用来创建更复杂的界面元素,例如一个图像与一段文字的组合,或是按钮悬浮在图像上方。
kotlin
@Composable
fun OverlayBoxExample() {
Box(
modifier = Modifier
.size(200.dp)
.background(Color.DarkGray)
) {
Image(
painter = painterResource(id = R.drawable.image),
contentDescription = "Background Image",
contentScale = ContentScale.Crop
)
Text(
"Overlay Text",
style = TextStyle(color = Color.White, fontSize = 16.sp),
modifier = Modifier
.align(Alignment.BottomStart)
.padding(8.dp)
)
FloatingActionButton(
onClick = { /* Handle click */ },
modifier = Modifier.align(Alignment.TopEnd),
content = { Icon(Icons.Default.Add, contentDescription = "Add") }
)
}
}
以下是一个简单的示例,演示如何在 Jetpack Compose 中实现弹出菜单。
kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.treevalue.jetsnack.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
PopupMenuDemo()
}
}
}
}
}
@Composable
fun PopupMenuDemo() {
var expanded by remember { mutableStateOf(false) }
var selectedItem by remember { mutableStateOf("None") }
Column(
modifier = Modifier.padding(16.dp)
) {
Button(onClick = { expanded = true }) {
Text(text = "Show Menu")
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(onClick = {
expanded = false
selectedItem = "Item 1"
}) {
Text("Item 1")
}
DropdownMenuItem(onClick = {
expanded = false
selectedItem = "Item 2"
}) {
Text("Item 2")
}
DropdownMenuItem(onClick = {
expanded = false
selectedItem = "Item 3"
}) {
Text("Item 3")
}
}
Text(text = "Selected: $selectedItem", modifier = Modifier.padding(top = 16.dp))
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApplicationTheme {
PopupMenuDemo()
}
}
-
Button 和 DropdownMenu:
Button
用于触发弹出菜单的显示。DropdownMenu
是实际的弹出菜单组件,expanded
参数控制菜单的显示与隐藏,onDismissRequest
在菜单外点击时触发,用于关闭菜单。
-
DropdownMenuItem:
DropdownMenuItem
定义了菜单中的各个项,点击时会触发对应的操作。
-
状态管理:
- 使用
remember
和mutableStateOf
来管理菜单的显示状态 (expanded
) 以及选中的菜单项 (selectedItem
)。
- 使用
一个简单的响应式网格布局:
kotlin
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Card
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.Alignment
@Composable
fun ResponsiveLayout() {
val items = listOf("Item 1", "Item 2", "Item 3", "Item 4")
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
LazyColumn {
items(items) { item ->
Card(
modifier = Modifier
.padding(8.dp)
.fillMaxWidth(),
elevation = 4.dp
) {
Text(
text = item,
modifier = Modifier.padding(16.dp),
fontWeight = FontWeight.Bold
)
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun PreviewResponsiveLayout() {
ResponsiveLayout()
}
响应式设计可以使用 BoxWithConstraints
来实现:
kotlin
@Composable
fun ResponsiveBoxLayout() {
BoxWithConstraints {
if (maxWidth < 600.dp) {
ColumnLayout()
} else {
RowLayout()
}
}
}
@Composable
fun ColumnLayout() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "Column Layout", modifier = Modifier.padding(16.dp))
}
}
@Composable
fun RowLayout() {
Row(
modifier = Modifier.fillMaxSize(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "Row Layout", modifier = Modifier.padding(16.dp))
}
}
@Preview(showBackground = true)
@Composable
fun PreviewResponsiveBoxLayout() {
ResponsiveBoxLayout()
}
使用 Jetpack Compose 实现页面显示和用户动态交互的示例。
1. 创建简单的 UI 和交互
kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApp()
}
}
}
@Composable
fun MyApp() {
var count by remember { mutableStateOf(0) }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "Count: $count", style = MaterialTheme.typography.h4)
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = { count++ }) {
Text("Increment")
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApp()
}
MainActivity
中的setContent
方法用于设置 Compose 的内容。MyApp
是主要的 Composable 函数,它包含一个计数器和一个按钮。remember
和mutableStateOf
用于在状态变化时重新组合 UI。Column
用于垂直排列元素,Spacer
用于增加间距,Button
用于用户交互。
2. 添加更多交互
添加一个文本输入框和显示用户输入的内容:
kotlin
@Composable
fun MyApp() {
var count by remember { mutableStateOf(0) }
var text by remember { mutableStateOf("") }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "Count: $count", style = MaterialTheme.typography.h4)
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = { count++ }) {
Text("Increment")
}
Spacer(modifier = Modifier.height(16.dp))
TextField(
value = text,
onValueChange = { text = it },
label = { Text("Enter text") }
)
Spacer(modifier = Modifier.height(16.dp))
Text(text = "You typed: $text")
}
}
在按钮点击时显示一个弹出菜单:
kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Button
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.treevalue.jetsnack.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme{
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
PopupMenuExample()
}
}
}
}
}
@Composable
fun PopupMenuExample() {
var expanded by remember { mutableStateOf(false) }
Column {
Button(onClick = { expanded = true }) {
Text("Show Menu")
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(onClick = { /* Handle action */ }) {
Text("Option 1")
}
DropdownMenuItem(onClick = { /* Handle action */ }) {
Text("Option 2")
}
DropdownMenuItem(onClick = { /* Handle action */ }) {
Text("Option 3")
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApplicationTheme{
PopupMenuExample()
}
}
- MainActivity : 设置Compose的内容,并在主题中包含一个示例组件
PopupMenuExample
。 - PopupMenuExample :
- 使用
remember
和mutableStateOf
创建一个expanded
状态变量,用于控制菜单的显示状态。 - 一个按钮点击时设置
expanded
为true
,显示弹出菜单。 DropdownMenu
用于创建弹出菜单,当expanded
为true
时显示,并在onDismissRequest
时将expanded
设置为false
以关闭菜单。DropdownMenuItem
用于定义菜单项及其点击事件。
- 使用
在 Jetpack Compose 中实现一个向左弹出的菜单:
kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import com.treevalue.jetsnack.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApp()
}
}
}
@Composable
fun MyApp() {
var expanded by remember { mutableStateOf(false) }
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Text(
text = "Click me",
modifier = Modifier
.clickable { expanded = true }
.padding(16.dp)
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false },
offset = DpOffset(Dp(-100f), Dp(0f)) // 向左偏移 100 像素
) {
DropdownMenuItem(
content = { Text("Option 1") },
onClick = { /* Handle option 1 click */ }
)
DropdownMenuItem(
content = { Text("Option 2") },
onClick = { /* Handle option 2 click */ }
)
DropdownMenuItem(
content = { Text("Option 3") },
onClick = { /* Handle option 3 click */ }
)
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApplicationTheme{
MyApp()
}
}
MyApp
组合函数定义了一个文本组件Text
,当点击时,会将expanded
状态设为true
,从而显示下拉菜单。DropdownMenu
组件的expanded
参数控制菜单的显示和隐藏,onDismissRequest
参数定义菜单被取消时的处理。offset
参数使用IntOffset
,其中第一个值为横向偏移量(负值向左偏移),第二个值为纵向偏移量。