Button을 눌러 Image를 바꾸는 방법을 Compose로 작성했다.
예전에 Button 50번 누르면 이미지가 바뀌는 코드를 작성한적 있 었는데 그 코드는 잃어버렸다! 엄청 간단한 코드였는데 아쉽다.
그래서 챗지피티한테 새로운 코드를 배웠고 유용할 것 같아서 저장한다. 특히 아래 두번째 코드가 유용할 것 같다.
설명 :
1. 변경 Button을 클릭하면, 이미지가 바뀜
2. Button을 누를 때마다 첫번째 이미지, 두번째 이미지가 바뀜
도움 :
챗지피티
ImageTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
var isPineappleVisible by remember { mutableStateOf(true) }
Column (
modifier = Modifier
.align(Alignment.Center),
horizontalAlignment = Alignment.CenterHorizontally) {
Image(
painter = painterResource(id = if (isPineappleVisible) R.drawable.pineapplepizza else R.drawable.burn1),
contentDescription = null,
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
isPineappleVisible = !isPineappleVisible
}
) {
Text(text = "변경")
}
}
}
}
}
}
}
설명 :
1. 변경하고 싶은 이미지 list 생성
2. 변경 button을 누를 때마다 list안에 이미지 바뀜
장점 :
이미지를 추가하기만 하면 되서 이미지를 많이 추가할 수 있음
단점 :
onClick 안에 코드가 이해가 안감! ㅎㅎㅎ
선생님이 이해해보라고 했는데 좀있다가 다시 공부해볼 예정임
var imageIndex by remember { mutableStateOf(0) }
var imageList = listOf(
R.drawable.pineapplepizza,
R.drawable.burn1,
R.drawable.burn2
)
Column (horizontalAlignment = Alignment.CenterHorizontally) {
Image(
painter = painterResource(id = imageList[imageIndex]),
contentDescription = null,
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
imageIndex = (imageIndex + 1) % imageList.size
}
) {
Text(text = "변경")
}
}
}
}
}
}
}```