[Android/Kotlin] 코틀린 파일에서 색상 다루는 법 - String, Int

코코아의 개발일지·2024년 8월 12일
5

Android-Kotlin

목록 보기
30/31
post-thumbnail

🤔 시작하기에 앞서

캘린더 앱을 만드는 프로젝트를 하면서 색을 정말 많이 다뤘다. 특히 리사이클러뷰를 이용해 색을 넣어줘야했기 때문에 xml이 아닌 코틀린 파일에서 색을 다뤘어야 했다. 따라서! 오늘은 색상 및 리소스 변경 🌟완벽 정리🌟 해보려고 한다.

😱 내가 부딪힌 어려움??

생각보다.. 관련되어 잘 정리되어 있는 자료를 찾기 힘들었던 것 같다. 처음에 문제에 직면했을 때는 어떻게 해결할지 감도 오지 않았었다.
나는 이것저것 테스트해보며 여러 방법으로 진행했다.

관련해서 정리해두었던 사진이다. 저 때가 Android 개발이 아예 처음이라 막막하기만 했던 시절이다. 추억 삼아 첨부한다.


💻 코드 정리

1️⃣ CardView

1. 색이 String 형태일 때

binding.itemPaletteColorCv.setCardBackgroundColor(Color.parseColor("#FFFFFF")

Hex 코드를 바로 쓸 수 있다는 점은 편하지만, 일일이 색을 지정해줘야한다는 번거로움이 있다.

2. 색이 Int 형태일 때

binding.itemPaletteColorCv.background.setTint(context.resources.getColor(R.color.white))
//혹은
binding.itemPaletteColorCv.setCardBackgroundColor(ContextCompat.getColor(context, R.color.white))

리소스 파일에 저장한 색상을 바로 활용할 수 있어 좋았다.

  • 해당 화면이 Activity이냐, Fragment이냐, Adapter이냐에 따라 context 부분을 다르게 써야할 수 있음

2️⃣ TextView

1. 색이 String 형태일 때

textView.setTextColor(Color.parseColor("#FFFFFF"))

2. 색이 Int 형태일 때

textView.setTextColor(ContextCompat.getColor(context, R.color.white))
//혹은 deprecated 되긴 했지만
textView.setTextColor(resources.getColor(R.color.white))

3️⃣ 배경 Background

1. drawable 리소스 자체를 변경

itemBG.setBackgroundResource(R.drawable.style_weekly_calendar_circle_selected)

2. 색만 변경

itemBG.backgroundTintList = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.white)) // Int
itemBG.backgroundTintList = ColorStateList.valueOf(Color.parseColor("#FFFFFF")); // String
itemBG.background.setTint(context.resources.getColor(R.color.white))

배경은 그대로인데 색만 바꿔줘야하는 경우 유용한 방법이다. (ex. 버튼 활성화)

📚 참고

* CardView의 xml 사용 예시

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.cardview.widget.CardView
        android:id="@+id/item_palette_color_cv"
        android:layout_marginStart="15dp"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="1dp"
        app:cardBackgroundColor="@color/categoryGray"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        style="@style/category_cv">
        <ImageView
            android:id="@+id/item_palette_select_iv"
            style="@style/img_category_check"/>
    </androidx.cardview.widget.CardView>


</androidx.constraintlayout.widget.ConstraintLayout>
profile
우당탕탕 성장하는 개발자

0개의 댓글