반응형
다음과 같은 View가 구성되어 있다고 가정해 보겠습니다.
<LinearLayout
android:id="@+id/addButton"
android:layout_width="100dp"
android:layout_height="40dp"
android:background="@drawable/home_add_btn_background"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingHorizontal="16dp"
android:paddingVertical="8dp">
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/transparent" />
<corners android:radius="8dp" />
<stroke android:width="1dp" android:color="#E0E0E0" />
</shape>
- home_add_btn_background
여기서 간혹 테마 설정 및 각종 효과를 위해 테두리의 색상을 변경하고 싶을 때가 있습니다.
이 경우 view의 background 또는 foreground의 속성을 수정해 주면 됩니다.
단, 코틀린 코드에서 XML로 정의된 shape의 stroke 색상을 동적으로 변경하려면 GradientDrawable을 수정해야 합니다.
GradientDrawable이란 Android에서 사용되는 그래픽 객체로, 그라데이션(Gradient), 모서리 반경(Corner Radius), 테두리(Stroke), 배경 색상(Solid Color) 등을 설정할 수 있는 유연한 도구입니다.
XML 파일이나 코드에서 정의할 수 있고, 주로 뷰의 배경으로 사용됩니다.
예시 코드)
val gradientDrawable = GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT, // 방향
intArrayOf(Color.RED, Color.YELLOW) // 색상 배열 (빨강 → 노랑)
).apply {
shape = GradientDrawable.RECTANGLE // 사각형
cornerRadius = 16f // 모서리 반경
setStroke(4, Color.BLACK) // 테두리
}
// 뷰에 적용
view.background = gradientDrawable
이를 사용하여 기존 background를 GradientDrawable로 가져오고, 속성 변경을 진행해 주면 됩니다.
fun Int.dpToPx(): Int = (this * Resources.getSystem().displayMetrics.density).toInt()
if (button != null && button.background is GradientDrawable) {
val background = button.background as GradientDrawable
background.setStroke(1.dpToPx(), getColor())
}
+) setStroke에서 두께는 픽셀(px) 단위로 전달해야 하므로, dp를 px로 변환하는 함수를 구현했습니다.
반응형