Jetpack Compose 教學上課講義【從零開始學 Jetpack Compose 程式設計】LazyColumn 列表資料佈局方式
【從零開始學 Jetpack Compose 程式設計】
線上教學課程目錄: https://bit.ly/3JF4SFA
Youtube 課程播放清單:https://bit.ly/3tFjRbx
Udemy 線上課程:https://bit.ly/3MbVnhO
【從零開始學 Jetpack Compose 程式設計】
線上教學課程目錄: https://bit.ly/3JF4SFA
Youtube 課程播放清單:https://bit.ly/3tFjRbx
Udemy 線上課程:https://bit.ly/3MbVnhO
不能滾動的列表
repeat 方便的 for 迴圈(初始值、條件式、更新方式)
Column {
repeat(1000) {
Text(
text = "HKT線上教室 $it",
style = MaterialTheme.typography.subtitle1
)
}
}
沒有回收機制的滾動列表
val scrollState = rememberScrollState()
Column(
Modifier
.verticalScroll(scrollState)
.fillMaxSize()
) {
repeat(1000) {
Text(
text = "HKT線上教室 $it",
style = MaterialTheme.typography.subtitle1
)
}
}
LazyColumn
val scrollState = rememberLazyListState()
LazyColumn(
modifier = Modifier.fillMaxSize(),
state = scrollState
) {
items(1000) {
Text(
text = "HKT線上教室 $it",
style = MaterialTheme.typography.subtitle1
)
}
}
作業
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
Demo()
}
}
}
}
@Composable
fun Demo() {
Scaffold(
topBar = {
TopAppBar(
title = { Text("HKT線上教室") },
)
}
) {
//畫面內容
WeatherScreen(FakeWeatherData.sample)
}
}
object FakeWeatherData {
val sample = listOf(
Location(
name = "台北市",
state = "今天會下雨"
),
Location(
name = "高雄市",
state = "今天天氣熱"
)
)
}
@Composable
fun WeatherScreen(locations: List<Location>) {
LazyColumn {
items(locations) { location ->
WeatherCard(location)
}
}
}
@Composable
fun WeatherCard(location: Location) {
Row(
Modifier
.padding(all = 20.dp)
.background(MaterialTheme.colors.background)
.fillMaxHeight(),
verticalAlignment = Alignment.CenterVertically,
) {
Image(
painter = painterResource(R.drawable.hktlogo),
contentDescription = null,
Modifier
.size(40.dp)
.clip(CircleShape)
)
Column(
Modifier
.padding(start = 20.dp)
) {
Text(
text = location.name,
style = MaterialTheme.typography.subtitle1
)
Spacer(
Modifier.height(4.dp)
)
Text(
text = location.state,
style = MaterialTheme.typography.subtitle2
)
}
}
}
data class Location(val name: String, val state: String)