Android中Compose常用組件及布局使用方法示例詳解
一、基礎(chǔ)控件詳解
1. Text - 文本控件
Text(
text = "Hello Compose", // 必填,顯示文本
color = Color.Blue, // 文字顏色
fontSize = 24.sp, // 字體大?。ㄗ⒁馐褂?sp單位)
fontStyle = FontStyle.Italic, // 字體樣式(斜體)
fontWeight = FontWeight.Bold, // 字體粗細(xì)
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:字體粗細(xì)(FontWeight.Normal,Bold,W800等)modifier:通用修飾符(設(shè)置邊距、背景、點(diǎn)擊事件等)maxLines:最大行數(shù)(超出顯示省略號)textDecoration:文本裝飾(TextDecoration.Underline下劃線)
效果(示意圖):
[淺灰色背景] Hello Compose(藍(lán)色,24sp,粗體,斜體)
2. Button - 按鈕控件
val context = LocalContext.current
Button(
onClick = { // 必填,點(diǎn)擊回調(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( // 圖標(biāo)
imageVector = Icons.Filled.Favorite,
contentDescription = "Like"
)
Spacer(Modifier.width(8.dp)) // 間距
Text("Like") // 按鈕文字
}核心參數(shù)說明:
onClick:點(diǎn)擊事件回調(diào)(必填)colors:顏色配置(背景色、文字色)enabled:是否啟用(false時(shí)變灰色)content:按鈕內(nèi)容(可包含任意Composable)
效果:
[紅色按鈕] ? Like(白色文字) 點(diǎn)擊后彈出Toast
3. TextField - 輸入框控件
var text by remember { mutableStateOf("") } // 關(guān)鍵:狀態(tài)管理
TextField(
value = text, // 當(dāng)前值(綁定狀態(tài))
onValueChange = { newText -> // 輸入變化回調(diào)
text = newText
},
label = { Text("Username") }, // 浮動(dòng)標(biāo)簽
placeholder = { Text("Enter your name") }, // 提示文字
leadingIcon = { // 前綴圖標(biāo)
Icon(Icons.Filled.Person, null)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text, // 鍵盤類型
imeAction = ImeAction.Done // 鍵盤動(dòng)作
),
modifier = Modifier.fillMaxWidth()
)核心參數(shù)說明:
value/onValueChange:必須配合狀態(tài)管理(remember+mutableStateOf)label:浮動(dòng)標(biāo)簽(輸入時(shí)上?。?/p>placeholder:提示文本(未輸入時(shí)顯示)keyboardOptions:鍵盤配置(郵箱/數(shù)字鍵盤等)singleLine:是否單行(true時(shí)禁用換行)
4. Image - 圖片控件
// 加載本地資源
Image(
painter = painterResource(R.drawable.dog),
contentDescription = "Cute dog", // 必填(無障礙)
modifier = Modifier
.size(120.dp)
.clip(CircleShape), // 圓形裁剪
contentScale = ContentScale.Crop // 裁剪模式
)
// 加載網(wǎng)絡(luò)圖片(Coil)
AsyncImage(
model = "https://example.com/image.jpg",
contentDescription = "Network image",
placeholder = { // 加載中顯示
CircularProgressIndicator()
},
error = { // 錯(cuò)誤顯示
Icon(Icons.Filled.Error, null)
}
)核心參數(shù)說明:
painter:本地資源(painterResource())contentDescription:必填(無障礙支持)contentScale:縮放模式(Crop,Fit,Inside等)alpha:透明度(0.0f-1.0f)colorFilter:顏色濾鏡(如黑白效果)
5. ProgressIndicator - 進(jìn)度指示器
// 圓形進(jìn)度條
CircularProgressIndicator(
progress = 0.7f, // 進(jìn)度值(0-1)
color = Color.Green,
strokeWidth = 8.dp,
modifier = Modifier.size(50.dp)
)
// 線性進(jìn)度條
LinearProgressIndicator(
progress = 0.4f,
backgroundColor = Color.LightGray,
color = MaterialTheme.colors.primary,
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)參數(shù)說明:
progress:進(jìn)度值(0-1),不傳則為不確定進(jìn)度color:進(jìn)度條顏色strokeWidth:圓形進(jìn)度條粗細(xì)backgroundColor:線性進(jìn)度條背景色
二、核心布局詳解(附結(jié)構(gòu)圖)
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 | 子項(xiàng)水平對齊 | Start, CenterHorizontally, End |
verticalArrangement | 垂直分布方式 | Top, Center, SpaceBetween, SpaceEvenly |
modifier | 修飾符 | 設(shè)置尺寸/背景/邊距等 |
布局效果:
┌───────────────────────────┐ │ │ │ Item 1 │ │ │ │ [ Button ] │ │ │ │ [圖標(biāo)] │ │ │ └───────────────────────────┘ (等間距分布)
2. Row - 水平布局
Row(
modifier = Modifier
.fillMaxWidth()
.background(Color.LightGray)
.padding(16.dp)
.horizontalScroll(rememberScrollState()), // 水平滾動(dòng)
verticalAlignment = Alignment.CenterVertically, // 垂直居中
horizontalArrangement = Arrangement.SpaceBetween // 兩端對齊
) {
Icon(Icons.Filled.Menu, "Menu")
Text("Title", fontWeight = FontWeight.Bold)
Icon(Icons.Filled.Search, "Search")
}參數(shù)說明:
| 參數(shù) | 說明 | 常用值 |
|---|---|---|
verticalAlignment | 子項(xiàng)垂直對齊 | Top, CenterVertically, Bottom |
horizontalArrangement | 水平分布方式 | Start, Center, SpaceBetween, SpaceAround |
.horizontalScroll() | 水平滾動(dòng)支持 | 必須添加 |
布局效果:
┌─[菜單]─────標(biāo)題─────[搜索]─┐ (兩端對齊,可橫向滾動(dòng))
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")
}
}關(guān)鍵方法:
Modifier.align():在Box內(nèi)定位Alignment.TopStartAlignment.CenterAlignment.BottomEnd
Modifier.zIndex():控制層級(默認(rèn)后添加的在上層)
布局效果:
┌───────────────────────────┐ │ [背景圖片] │ │ │ │ 居中文字 │ │ │ │ [按鈕] │ └───────────────────────────┘ (三層疊加)
三、常見問題
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:如何實(shí)現(xiàn)列表滾動(dòng)?
垂直滾動(dòng):
Column(
modifier = Modifier.verticalScroll(rememberScrollState())
) { /* 長內(nèi)容 */ }高性能列表(LazyColumn):
LazyColumn {
item { Header() }
items(100) { index -> // 只渲染可見項(xiàng)
ListItem(index)
}
item { Footer() }
}Q3:Box 布局如何實(shí)現(xiàn)復(fù)雜定位?
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:如何實(shí)現(xiàn)響應(yīng)式布局?
@Composable
fun AdaptiveLayout() {
// 根據(jù)屏幕寬度選擇布局
val configuration = LocalConfiguration.current
val screenWidth = configuration.screenWidthDp.dp
if (screenWidth < 600.dp) {
VerticalLayout() // 小屏:垂直布局
} else {
HorizontalLayout() // 大屏:水平布局
}
}到此這篇關(guān)于Android中Compose常用組件以及布局使用方法的文章就介紹到這了,更多相關(guān)android compose組件布局內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android實(shí)現(xiàn)跳動(dòng)的小球加載動(dòng)畫效果
Android中有各式各樣的加載動(dòng)畫,大家多多少少都見過,比如用過美團(tuán)客戶端的用戶對美團(tuán)那個(gè)加載小人的動(dòng)畫印象很深刻,一個(gè)可愛的小人在那拼命的跑。這樣的動(dòng)畫實(shí)現(xiàn)其實(shí)還有很多,今天這里就來實(shí)現(xiàn)一個(gè)跳動(dòng)的小球效果。有需要的可以參考借鑒。2016-08-08
Android自定義view實(shí)現(xiàn)水波紋進(jìn)度球效果
在我們的日常開發(fā)中自定義控件還是用的挺多的,設(shè)計(jì)師或者產(chǎn)品為了更好的漂亮,美觀,交互都會(huì)做一些牛逼的ui效果圖,但是最后實(shí)現(xiàn)的還是我們程序員啊。所以說 自定義view你還是得會(huì)的。2016-08-08
解析:繼承ViewGroup后的子類如何重寫onMeasure方法
本篇文章是對繼承ViewGroup后的子類如何重寫onMeasure方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
Framework源碼面試之a(chǎn)ctivity啟動(dòng)流程
這篇文章主要為大家介紹了Framework源碼面試之a(chǎn)ctivity啟動(dòng)流程實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
Android ViewPager相冊橫向移動(dòng)的實(shí)現(xiàn)方法
本篇文章小編為大家介紹,Android ViewPager相冊橫向移動(dòng)的實(shí)現(xiàn)方法。需要的朋友參考下2013-04-04
Android AnalogClock簡單使用方法實(shí)例
這篇文章主要介紹了Android AnalogClock簡單使用方法,結(jié)合實(shí)例形式簡單分析了AnalogClock的布局調(diào)用技巧,需要的朋友可以參考下2016-01-01

