코두까기 (코드를 하나씩 까보자)
기본 처음 시작될 때 생성되는 코드
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MySnackBar() // <- 좀있다 생성할 함수명
}
}
}
remember : : 메모리에 단일 객체를 저장 , 반환 하는 역할 / 즉, 값을 새로 생성하지 않고 기존에 저장되어 있던 데이터를 반환한다는 의미
@Composable
fun MySnackBar() {
val snackBarState = remember { SnackbarHostState() }
val coroutineScope = rememberCoroutineScope()
val buttonTitle: (SnackbarData?) -> String = { snackbarData ->
if (snackbarData != null) {
"스낵바 숨기기"
} else {
"스낵바 보여주기"
}
}
val buttonColor: (SnackbarData?) -> Color = { snackbarData ->
if (snackbarData != null) {
Color.Black
} else {
Color.Blue
}
}
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Button(colors= ButtonDefaults.buttonColors(
backgroundColor = buttonColor(snackBarState.currentSnackbarData),
contentColor = Color.White
),
onClick = {
if (snackBarState.currentSnackbarData !=null){
snackBarState.currentSnackbarData?.dismiss()
return@Button
}
coroutineScope.launch {
val result = snackBarState.showSnackbar(
"가즈아 빡코딩",
"확인",
SnackbarDuration.Short
).let {
when (it) {
SnackbarResult.Dismissed -> Log.d("TAG", "스낵바 닫아짐")
SnackbarResult.ActionPerformed -> Log.d("TAG", "MYSnackBar: 스낵바 확인 버튼 클릭")
}
}
}
}) {
Text(buttonTitle(snackBarState.currentSnackbarData))
}
SnackbarHost(hostState = snackBarState, modifier = Modifier.align(Alignment.BottomCenter))
}
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MySnackBar()
}
}
}
@Composable
fun MySnackBar() {
val snackBarState = remember { SnackbarHostState() }
val coroutineScope = rememberCoroutineScope()
val buttonTitle: (SnackbarData?) -> String = { snackbarData ->
if (snackbarData != null) {
"스낵바 숨기기"
} else {
"스낵바 보여주기"
}
}
val buttonColor: (SnackbarData?) -> Color = { snackbarData ->
if (snackbarData != null) {
Color.Black
} else {
Color.Blue
}
}
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Button(colors= ButtonDefaults.buttonColors(
backgroundColor = buttonColor(snackBarState.currentSnackbarData),
contentColor = Color.White
),
onClick = {
if (snackBarState.currentSnackbarData !=null){
snackBarState.currentSnackbarData?.dismiss()
return@Button
}
coroutineScope.launch {
val result = snackBarState.showSnackbar(
"가즈아 빡코딩",
"확인",
SnackbarDuration.Short
).let {
when (it) {
SnackbarResult.Dismissed -> Log.d("TAG", "스낵바 닫아짐")
SnackbarResult.ActionPerformed -> Log.d("TAG", "MYSnackBar: 스낵바 확인 버튼 클릭")
}
}
}
}) {
Text(buttonTitle(snackBarState.currentSnackbarData))
}
SnackbarHost(hostState = snackBarState, modifier = Modifier.align(Alignment.BottomCenter))
}
}