codelab 에서 만들 앱의 내용을 확인할 수 있다.
Composable함수에서 상태를 저장하여 버튼을 누를 때 마다 imageNumber의 값이 변경되고 변경된 값에 따라 저장된 상태들의 값을 주었다.
var imageNumber by remember { mutableStateOf(0) }
var title by remember { mutableStateOf("") }
var artist by remember { mutableStateOf("") }
var year by remember { mutableStateOf("") }
var previous by remember { mutableStateOf(false) } //이전버튼 활성/비활성
var next by remember { mutableStateOf(true) } //다음버튼 활성/비활성
val imagePainter = when (imageNumber) {
0 -> {
title = stringResource(id = R.string.a1title)
artist = stringResource(id = R.string.a1by)
year = stringResource(id = R.string.a1year)
previous=false
R.drawable.a1
}
1 -> {
title = stringResource(id = R.string.a2title)
artist = stringResource(id = R.string.a2by)
year = stringResource(id = R.string.a2year)
previous=true
next=true
R.drawable.a2
}
...
상태 호이스팅을 위해 상태들을 최상위 함수에 정의하였고 최상위 함수에서 상태 인자를 전달한다.
Column(
modifier = Modifier
.fillMaxWidth()
.padding(top = 40.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
ImageLoad(
painter = imagePainter,
description = title,
Modifier
.padding(start = 24.dp, end = 24.dp, top = 18.dp, bottom = 10.dp)
.wrapContentHeight(Alignment.CenterVertically)
.weight(0.4f)
)
ImageInfo(
title = title, author = artist, year = year,
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight(Alignment.CenterVertically)
.padding(start = 24.dp, end = 24.dp, bottom = 20.dp, top = 40.dp)
)
Row(
Modifier
.padding(start = 24.dp, end = 24.dp, bottom = 15.dp)
.fillMaxWidth()
.weight(0.1f)
.wrapContentHeight(Alignment.Bottom),
horizontalArrangement = Arrangement.SpaceEvenly
) {
ImageButton(
text = "Previous",
onClick = {
imageNumber--
},
check = previous)
ImageButton(
text = "Next",
onClick = {
imageNumber++
},check = next)
}
}