Android中Compose常用組件及布局使用方法示例詳解
一、基礎控件詳解
1. Text - 文本控件
Text( text = "Hello Compose", // 必填,顯示文本 color = Color.Blue, // 文字顏色 fontSize = 24.sp, // 字體大小(注意使用.sp單位) fontStyle = FontStyle.Italic, // 字體樣式(斜體) fontWeight = FontWeight.Bold, // 字體粗細 modifier = Modifier .padding(16.dp) // 內(nèi)邊距 .background(Color.LightGray) // 背景色 )
核心參數(shù)說明:
text
:顯示的文字內(nèi)容(必填)color
:文字顏色(Color.Red
,Color(0xFF6200EE)
等)fontSize
:字體大?。ū仨毷褂?code>.sp單位,如18.sp
)fontWeight
:字體粗細(FontWeight.Normal
,Bold
,W800
等)modifier
:通用修飾符(設置邊距、背景、點擊事件等)maxLines
:最大行數(shù)(超出顯示省略號)textDecoration
:文本裝飾(TextDecoration.Underline
下劃線)
效果(示意圖):
[淺灰色背景] Hello Compose(藍色,24sp,粗體,斜體)
2. Button - 按鈕控件
val context = LocalContext.current Button( onClick = { // 必填,點擊回調(diào) Toast.makeText(context, "Clicked!", Toast.LENGTH_SHORT).show() }, colors = ButtonDefaults.buttonColors( backgroundColor = Color.Red, // 按鈕背景 contentColor = Color.White // 內(nèi)容顏色 ), modifier = Modifier.padding(8.dp), enabled = true // 是否啟用 ) { Icon( // 圖標 imageVector = Icons.Filled.Favorite, contentDescription = "Like" ) Spacer(Modifier.width(8.dp)) // 間距 Text("Like") // 按鈕文字 }
核心參數(shù)說明:
onClick
:點擊事件回調(diào)(必填)colors
:顏色配置(背景色、文字色)enabled
:是否啟用(false時變灰色)content
:按鈕內(nèi)容(可包含任意Composable)
效果:
[紅色按鈕] ? Like(白色文字) 點擊后彈出Toast
3. TextField - 輸入框控件
var text by remember { mutableStateOf("") } // 關鍵:狀態(tài)管理 TextField( value = text, // 當前值(綁定狀態(tài)) onValueChange = { newText -> // 輸入變化回調(diào) text = newText }, label = { Text("Username") }, // 浮動標簽 placeholder = { Text("Enter your name") }, // 提示文字 leadingIcon = { // 前綴圖標 Icon(Icons.Filled.Person, null) }, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, // 鍵盤類型 imeAction = ImeAction.Done // 鍵盤動作 ), modifier = Modifier.fillMaxWidth() )
核心參數(shù)說明:
value
/onValueChange
:必須配合狀態(tài)管理(remember+mutableStateOf
)label
:浮動標簽(輸入時上?。?/p>placeholder
:提示文本(未輸入時顯示)keyboardOptions
:鍵盤配置(郵箱/數(shù)字鍵盤等)singleLine
:是否單行(true時禁用換行)
4. Image - 圖片控件
// 加載本地資源 Image( painter = painterResource(R.drawable.dog), contentDescription = "Cute dog", // 必填(無障礙) modifier = Modifier .size(120.dp) .clip(CircleShape), // 圓形裁剪 contentScale = ContentScale.Crop // 裁剪模式 ) // 加載網(wǎng)絡圖片(Coil) AsyncImage( model = "https://example.com/image.jpg", contentDescription = "Network image", placeholder = { // 加載中顯示 CircularProgressIndicator() }, error = { // 錯誤顯示 Icon(Icons.Filled.Error, null) } )
核心參數(shù)說明:
painter
:本地資源(painterResource()
)contentDescription
:必填(無障礙支持)contentScale
:縮放模式(Crop
,Fit
,Inside
等)alpha
:透明度(0.0f-1.0f)colorFilter
:顏色濾鏡(如黑白效果)
5. ProgressIndicator - 進度指示器
// 圓形進度條 CircularProgressIndicator( progress = 0.7f, // 進度值(0-1) color = Color.Green, strokeWidth = 8.dp, modifier = Modifier.size(50.dp) ) // 線性進度條 LinearProgressIndicator( progress = 0.4f, backgroundColor = Color.LightGray, color = MaterialTheme.colors.primary, modifier = Modifier .fillMaxWidth() .padding(16.dp) )
參數(shù)說明:
progress
:進度值(0-1),不傳則為不確定進度color
:進度條顏色strokeWidth
:圓形進度條粗細backgroundColor
:線性進度條背景色
二、核心布局詳解(附結(jié)構圖)
1. Column - 垂直布局
Column( modifier = Modifier .fillMaxSize() // 占滿父布局 .background(Color.LightGray), horizontalAlignment = Alignment.CenterHorizontally, // 水平居中 verticalArrangement = Arrangement.SpaceEvenly // 等間距分布 ) { Text("Item 1") Button(onClick = {}) { Text("Button") } Image(painterResource(R.drawable.icon), null) }
參數(shù)說明:
參數(shù) | 說明 | 常用值 |
---|---|---|
horizontalAlignment | 子項水平對齊 | Start , CenterHorizontally , End |
verticalArrangement | 垂直分布方式 | Top , Center , SpaceBetween , SpaceEvenly |
modifier | 修飾符 | 設置尺寸/背景/邊距等 |
布局效果:
┌───────────────────────────┐ │ │ │ Item 1 │ │ │ │ [ Button ] │ │ │ │ [圖標] │ │ │ └───────────────────────────┘ (等間距分布)
2. Row - 水平布局
Row( modifier = Modifier .fillMaxWidth() .background(Color.LightGray) .padding(16.dp) .horizontalScroll(rememberScrollState()), // 水平滾動 verticalAlignment = Alignment.CenterVertically, // 垂直居中 horizontalArrangement = Arrangement.SpaceBetween // 兩端對齊 ) { Icon(Icons.Filled.Menu, "Menu") Text("Title", fontWeight = FontWeight.Bold) Icon(Icons.Filled.Search, "Search") }
參數(shù)說明:
參數(shù) | 說明 | 常用值 |
---|---|---|
verticalAlignment | 子項垂直對齊 | Top , CenterVertically , Bottom |
horizontalArrangement | 水平分布方式 | Start , Center , SpaceBetween , SpaceAround |
.horizontalScroll() | 水平滾動支持 | 必須添加 |
布局效果:
┌─[菜單]─────標題─────[搜索]─┐ (兩端對齊,可橫向滾動)
3. Box - 層疊布局
Box( modifier = Modifier .size(200.dp) .background(Color.Blue) ) { Image( // 底層 painter = painterResource(R.drawable.bg), contentDescription = "Background", modifier = Modifier.fillMaxSize() ) Text( // 中層 "Overlay Text", color = Color.White, modifier = Modifier .align(Alignment.Center) .padding(8.dp) ) Button( // 頂層 onClick = {}, modifier = Modifier .align(Alignment.BottomEnd) .padding(16.dp) ) { Text("Action") } }
關鍵方法:
Modifier.align()
:在Box內(nèi)定位Alignment.TopStart
Alignment.Center
Alignment.BottomEnd
Modifier.zIndex()
:控制層級(默認后添加的在上層)
布局效果:
┌───────────────────────────┐ │ [背景圖片] │ │ │ │ 居中文字 │ │ │ │ [按鈕] │ └───────────────────────────┘ (三層疊加)
三、常見問題
Q1:Compose 為什么需要狀態(tài)管理?TextField 如何處理狀態(tài)變化?
答:
// 狀態(tài)聲明 var text by remember { mutableStateOf("") } // 狀態(tài)綁定 TextField( value = text, // 綁定狀態(tài)值 onValueChange = { newText -> text = newText // 更新狀態(tài) } ) /* 1. 初始狀態(tài) text = "" 2. 用戶輸入 "A" -> 觸發(fā) onValueChange 3. text 更新為 "A" 4. 狀態(tài)變化觸發(fā)重組(Recomposition) 5. TextField 根據(jù)新值刷新界面 */
Q2:如何實現(xiàn)列表滾動?
垂直滾動:
Column( modifier = Modifier.verticalScroll(rememberScrollState()) ) { /* 長內(nèi)容 */ }
高性能列表(LazyColumn):
LazyColumn { item { Header() } items(100) { index -> // 只渲染可見項 ListItem(index) } item { Footer() } }
Q3:Box 布局如何實現(xiàn)復雜定位?
Box(modifier = Modifier.fillMaxSize()) { // 左上角 Text("TopStart", Modifier.align(Alignment.TopStart)) // 右上角 Button(onClick = {}, Modifier.align(Alignment.TopEnd)) { ... } // 正中央 Image(..., Modifier.align(Alignment.Center)) // 左下角 Icon(..., Modifier.align(Alignment.BottomStart)) // 右下角 CircularProgressIndicator(Modifier.align(Alignment.BottomEnd)) }
Q4:如何實現(xiàn)響應式布局?
@Composable fun AdaptiveLayout() { // 根據(jù)屏幕寬度選擇布局 val configuration = LocalConfiguration.current val screenWidth = configuration.screenWidthDp.dp if (screenWidth < 600.dp) { VerticalLayout() // 小屏:垂直布局 } else { HorizontalLayout() // 大屏:水平布局 } }
到此這篇關于Android中Compose常用組件以及布局使用方法的文章就介紹到這了,更多相關android compose組件布局內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Android?RecyclerView實現(xiàn)九宮格效果
這篇文章主要為大家詳細介紹了Android?RecyclerView實現(xiàn)九宮格效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-06-06Android應用中使用SharedPreferences類存儲數(shù)據(jù)的方法
這篇文章主要介紹了Android應用中使用SharedPreferences類存儲數(shù)據(jù)的方法,SharedPreferences使用鍵值對應的方式進行存儲,使用于少量的數(shù)據(jù)保存,需要的朋友可以參考下2016-04-04Android在OnCreate中獲取控件的寬度和高度的實現(xiàn)代碼
在Android中,有時需要對控件進行測量,得到的控件寬度和高度可以用來做一些計算。在需要自適應屏幕的情況下,這種計算就顯得特別重要2012-11-11