Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Kotlin으로 Android CheckBox 색상 변경하는 방법 완벽 가이드

이 튜토리얼에서는 Kotlin을 사용하여 Android 앱에서 CheckBox(체크박스)의 색상을 변경하는 방법을 단계별로 살펴봅니다. 버튼 클릭 시 체크박스의 텍스트 색상과 배경색을 동적으로 바꾸는 간단한 예제를 통해 실습해 보겠습니다.

1단계: 새 프로젝트 생성

Android Studio에서 새 프로젝트를 생성합니다. 상단 메뉴에서 File → New Project를 선택하고, 빈 Activity 템플릿을 기준으로 프로젝트 생성에 필요한 모든 정보를 입력합니다.

2단계: 레이아웃 파일 작성 (activity_main.xml)

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 안내 문구와 체크박스, 그리고 색상 변경용 버튼을 배치하는 구성입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Click the check box"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="16sp"
        android:textStyle="bold" />

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textView"
        android:layout_centerInParent="true"
        android:text="Check box" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/checkbox"
        android:layout_centerInParent="true"
        android:text="Change Color" />

</RelativeLayout>

3단계: MainActivity.kt 작성

src/MainActivity.kt 파일에 아래 코드를 추가합니다. 핵심은 두 가지 메서드입니다.

  • setTextColor(): 체크박스 텍스트의 색상을 지정합니다.
  • setBackgroundColor(): 체크박스 위젯 전체의 배경색을 지정합니다. Color.parseColor()를 사용하면 헥스 코드(#cbff75 등)로도 색상을 지정할 수 있습니다.
import android.graphics.Color
import android.os.Bundle
import android.widget.Button
import android.widget.CheckBox
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        val checkBox: CheckBox = findViewById(R.id.checkbox)
        val button: Button = findViewById(R.id.button)

        button.setOnClickListener {
            checkBox.setTextColor(Color.MAGENTA)
            checkBox.setBackgroundColor(Color.parseColor("#cbff75"))
        }
    }
}

4단계: AndroidManifest.xml 확인

androidManifest.xml 파일이 아래와 같이 설정되어 있는지 확인합니다. 별도의 권한 선언 없이 기본 구성만으로 실행할 수 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 Activity 파일 중 하나를 연 뒤, 툴바의 Run ▶ 아이콘을 클릭하세요. 실행할 기기 목록에서 연결된 모바일 기기를 선택하면, 해당 기기에 아래와 같은 기본 화면이 표시됩니다.

Kotlin으로 Android CheckBox 색상 변경하는 방법 완벽 가이드

Change Color 버튼을 누르면 체크박스의 텍스트가 마젠타(MAGENTA) 색으로 바뀌고, 배경색은 연두색 계열(#cbff75)로 즉시 변경되는 것을 확인할 수 있습니다.

추가 팁

버튼 클릭이 아니라 체크 상태가 변경될 때마다 색상을 바꾸고 싶다면 setOnCheckedChangeListener를 활용하면 됩니다. 또한 Material Design 컴포넌트를 사용하는 최신 프로젝트라면 MaterialCheckBox와 테마 속성(colorSecondary 등)을 통해 더 일관된 스타일로 체크박스 색상을 제어할 수도 있습니다.