App/Android
[Android/Kotlin] expandable + moveable/draggable Floating button (jetpack compose)
공부하곰
2024. 10. 23. 09:19
728x90
반응형
1. expandable floating button
참고: https://www.youtube.com/watch?app=desktop&v=9SHNfpnzdEU
유튜브 방법은 조금 복잡하다. 좀 더 간단하게 만들었다.
@Composable
fun ExpandableFloatingButton() {
var expanded by remember { mutableStateOf(false) } // 버튼 확장 여부를 추적
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.BottomEnd
) {
// 확장된 버튼들
Column(
horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.padding(end = 16.dp, bottom = 16.dp)
) {
if (expanded) {
FloatingActionButton(
onClick = { /* 첫 번째 버튼 액션 */ },
backgroundColor = Color.Blue
) {
Icon(Icons.Default.Add, contentDescription = "action 1")
}
FloatingActionButton(
onClick = { /* 두 번째 버튼 액션 */ },
backgroundColor = Color.Green
) {
Icon(Icons.Default.Check, contentDescription = "action 2")
}
FloatingActionButton(
onClick = { /* 세 번째 버튼 액션 */ },
backgroundColor = Color.Red
) {
Icon(Icons.Default.Close, contentDescription = "action 3")
}
}
// 메인 플로팅 버튼
FloatingActionButton(
onClick = { expanded = !expanded }, // 확장 여부 토글
backgroundColor = Color.Yellow
) {
Icon(
if (expanded) Icons.Default.KeyboardArrowDown else Icons.Default.KeyboardArrowUp,
contentDescription = "expansion"
)
}
}
}
}
2. moveable / draggable
위치 고정이 아니라 움직일 수 있는 floating button을 만들기.
Modifier.draggable을 사용하면 된다.
수직 방향 이동 - 수평 방향 이동이 가능한데 원하는 것만 넣어줘도 되고 둘 다 넣어줘도 되고...
아래 코드는 두 가지 다 추가한 것.
var offsetX by remember { mutableFloatStateOf(0f) }
var offsetY by remember { mutableFloatStateOf(0f) }
//...
modifier = Modifier
.offset { IntOffset(offsetX.roundToInt(), 0) } // 드래그에 따라 이동 , offsetY.roundToInt()
.draggable(
orientation = Orientation.Horizontal,
state = rememberDraggableState { deltaX ->
offsetX = (offsetX + deltaX).coerceIn(screenWidthPx, 0f)
}
)
.draggable(
orientation = Orientation.Vertical,
state = rememberDraggableState { deltaY ->
offsetY += deltaY
}
)
원래의 FloatingButton에 두 가지만 추가해주면 된다.
- Modifier.offset을 사용하여 버튼을 드래그할 때 이동할 위치를 설정
- Modifier.draggable을 사용하여 수평 및 수직으로 드래그할 수 있도록 적용
728x90
반응형