今天開始將使用 Jetpack Compose 實作一個簡單的專案,目標是製作一個訂閱紀錄應用程式。此應用程式的介面預計包含兩個主要頁面:一個是顯示所有訂閱項目的清單頁,另一個是用來新增或編輯訂閱項目的表單頁。在資料儲存方面,應用會將訂閱資料保存在本機端,以便用戶管理自己的訂閱紀錄。
首先先把Navigation建立好,因為到時候進到詳細頁會需要帶ID所以就一起傳遞過去。
@Composable
fun MainScreen(modifier: Modifier = Modifier) {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "home") {
composable("home") {
HomeScreen(navController = navController, modifier = modifier)
}
composable(route = "detail/{id}") {
DetailScreen(navController = navController, modifier = modifier)
}
}
}
接著首頁,因為清單是動態的因此使用LazyColumn來完成
@Composable
fun HomeScreen(navController: NavController, modifier: Modifier) {
val list = listOf(
SubscriptionViewData(name = "Apple TV", price = "$10/month"),
SubscriptionViewData(name = "Youtube Premium", price = "$10/month"),
SubscriptionViewData(name = "Apple Music", price = "$10/month"),
SubscriptionViewData(name = "Netflix", price = "$10/month"),
SubscriptionViewData(name = "Discord", price = "$10/month")
)
LazyColumn (
modifier = modifier.fillMaxWidth().fillMaxHeight()
) {
items(list) { item: SubscriptionViewData ->
SubscriptionItem(modifier = modifier, navController = navController, name = item.name, item.price)
}
}
}
Item的部分則先傳遞名稱跟價格,之後再補上Image
@Composable
fun SubscriptionItem(modifier: Modifier, navController: NavController, name: String, price: String) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth().padding(horizontal = 16.dp)
) {
Image(
painter = painterResource(R.drawable.ic_launcher_background),
contentDescription = "",
modifier = modifier.height(32.dp).width(32.dp)
)
Column(
modifier = modifier
.weight(1f)
.padding(8.dp)
) {
Text(
text = name,
fontSize = 24.sp
)
Text(
text = price
)
}
IconButton(onClick = {
}) {
Icon(
imageVector = Icons.AutoMirrored.Filled.ArrowForward,
contentDescription = "Localized description"
)
}
}
}
預覽結果
時間有點來不及因此今天就先做這樣,預計明天會開始做詳細頁以及ViewModel。