컴포즈 Button 정리

seunghee song·2024년 4월 28일

안드로이드 개발을 진행할 때 빠질 수 없는 컴포넌트인 Button을 컴포즈에서는 어떻게 디자인하고 인터랙션을 처리하는지에 대해 학습하였다.

우선 Compose에서 제공하는 Button은 다음과 같은 매개변수들이 있다.

fun Button(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    shape: Shape = ButtonDefaults.shape,
    colors: ButtonColors = ButtonDefaults.buttonColors(),
    elevation: ButtonElevation? = ButtonDefaults.buttonElevation(),
    border: BorderStroke? = null,
    contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    content: @Composable RowScope.() -> Unit
)

이를 하나씩 적용해보면서 알아보도록 하겠다.

우선 enable은 클릭여부를 처리하는 변수이다. 그리고 elevation은 버튼이 떠있는 정도를 정의할 수 있는데 사용법은 다음과 같다.

elevation = ButtonDefaults.buttonElevation(
                defaultElevation = 10.dp,
                //눌렀을때 그림자가 사라지는 효과
                pressedElevation = 0.dp,
                //버튼이 disabled되었을때 어떻게 처리할것인가 enable이 false일때
                disabledElevation = 0.dp
            ),
  • defaultElevation : elevation의 기본값이다.
  • pressedElevation: 버튼을 눌렀을때의 elevation값을 지정할 수 있다.
  • disabledElevation: 버튼이 disabled 상태일때의 elevation 값을 지정할 수 있다.
 onClick = {
            Log.d("TAG", " 버튼 1 클릭")
        })

당연하게도 onClick 매개변수로는 클릭했을 때의 이벤트를 생성할 수 있다.

또한 button들의 매개변수를 지정해 주고나면 버튼 내부에 들어갈 컴포넌트들을 넣을 수 있게된다. (예시-> Text와 같은 것들)

shape = RectangleShape,

Button에는 모양을 지정할 수 있는 매개변수도 있다.

  • CircleShape
  • RectangleShape
  • RoundedCornerShape

이렇게 3가지가 있으며 RoundedCornerShape는 모서리의 둥근 정도를 지정할 수 있다.

border = BorderStroke(width = 4.dp, color = Color.DarkGray),

이는 button의 외곽선을 지정할 수 있다.

val buttonBorderGradient = Brush.horizontalGradient(listOf(Color.Yellow, Color.Red))
border = BorderStroke(width = 4.dp, brush = buttonBorderGradient),

추가적으로 외곽선에 그라데이션을 줄 수 도 있다.

contentPadding = PaddingValues(horizontal = 20.dp, vertical = 5.dp),

이는 button 내부의 content에 대한 패딩을 지정할 수 있다.

그 다음으로 interactionSource라는 것이 있는데 이는 사용자의 인터랙션을 처리하는 매개변수이다.

val interactionSource = remember{ MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val pressStatusTitle = if(isPressed) "버튼을 누르고 있다" else "버튼에서 손을 뗐다"

Button(
            enabled = true,
            shape = RoundedCornerShape(10.dp),
            //stroke에 그라데이션 효과도 줄 수 있음
            border = BorderStroke(width = 4.dp, brush = buttonBorderGradient),
            colors = ButtonDefaults.buttonColors(
                //버튼의 배경색
              containerColor = Color.Black,
                contentColor = Color.LightGray
            ),
            elevation = ButtonDefaults.buttonElevation(
                defaultElevation = 10.dp,
                //눌렀을때 그림자가 사라지는 효과
                pressedElevation = 0.dp,
                //버튼이 disabled되었을때 어떻게 처리할것인가 enable이 false일때
                disabledElevation = 0.dp
            ),
            //여기에 interactionSource넣어주기
            interactionSource = interactionSource,
            onClick = {
                Log.d("TAG", " 버튼 4 클릭")
            }){
            //버튼에 대한 세부사항 지정하기
            Text(text = "버튼 4")
        }
        Text(text = "$pressStatusTitle")
  • MutableInteractionSource: 사용자와의 상호작용을 추적하는 객체이다. 버튼의 눌린 상태를 추적할 수 있고 이 코드에서는 그 상태를 기억하도록 하였다.
  • collectIsPressedAsState(): interactionSource에서 버튼이 눌렸는지의 여부 상태를 수집하고 isPressed 상태 값으로 변환한다.
  • pressStatusTitle: 이 코드상에서는 isPressed 값에 따라 동적으로 문자열을 변경하여 버튼의 상태를 설명하는 문자열을 정의하고 있다.

다음은 커스텀 그림자를 만들기 위한 실습이다.
링크텍스트

이 코드에서 커스텀 그림자를 만들기 위한 코드를 잘 설명해주고 있다. 따라서 이 코드를 가져다 사용하였다.

        Button(
            enabled = true,
            shape = RoundedCornerShape(10.dp),
            //stroke에 그라데이션 효과도 줄 수 있음
            border = BorderStroke(width = 4.dp, brush = buttonBorderGradient),
            colors = ButtonDefaults.buttonColors(
                //버튼의 배경색
                containerColor = Color.Black,
                contentColor = Color.LightGray
            ),
            elevation = ButtonDefaults.buttonElevation(
                defaultElevation = 0.dp,
                //눌렀을때 그림자가 사라지는 효과
                pressedElevation = 0.dp,
                //버튼이 disabled되었을때 어떻게 처리할것인가 enable이 false일때
                disabledElevation = 0.dp
            ),
            //여기에 interactionSource넣어주기
            interactionSource = interactionSourceForSecond,
            modifier = Modifier.drawColoredShadow(
                color = Color.Red,
                //투명도
                alpha = 0.5f,
                borderRadius = 0.dp,
                //퍼짐 정도
                shadowRadius = pressedBtnRadiusWithAnim,
                offsetY = 0.dp,
                offsetX = 0.dp
            ),
            onClick = {
                Log.d("TAG", " 버튼 5 클릭")
            }){
            //버튼에 대한 세부사항 지정하기
            Text(text = "버튼 5")
        }
    }

커스텀 그림자를 만들기 위한 매개변수들은 모두 피그마에 정의된 drop shadow와 똑같이 구현하기 위한 매개변수들이다.

profile
안드로이드 개발자

2개의 댓글

comment-user-thumbnail
2024년 4월 28일

천재인가요?

1개의 답글