[android : kotlin] 코틀린 setOnCheckedChangeListener() 사용 방법 및 Checkbox 사용 예제 (toggle())
코틀린 setOnCheckedChangeListener()
setOnCheckedChangeListener() 리스너는 사용자가 체크박스을 체크하거나 해제했을 때 반응하는 이벤트 처리를 하기 위해 사용된다. setOnCheckedChangeListener()를 사용하는 방법에는 inner class로 생성 후 사용하는 방법과 람다식을 사용하는 방법이 있다. 개발자 마다 좋아하는 코딩 스타일이 있으니 두 가지 방법 중에 아무거나 사용해도 된다. 람다식 방법으로 코딩시 미사용된 buttonView의 경우 언더바( _ )로 처리가 가능하다.
[MainActivity.kt]
package edu.kotlin.study
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.CompoundButton
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button1.setOnClickListener {
checkBox1.isChecked = true
checkBox2.isChecked = true
checkBox3.isChecked = true
}
button2.setOnClickListener {
checkBox1.isChecked = false
checkBox2.isChecked = false
checkBox3.isChecked = false
}
button3.setOnClickListener {
checkBox1.toggle()
checkBox2.toggle()
checkBox3.toggle()
}
button4.setOnClickListener {
if (checkBox1.isChecked) {
text1.text = "1번째 체크됨\n"
} else text1.text = "1번째 체크 헤제됨\n"
if (checkBox2.isChecked) {
text1.append("2번째 체크됨\n")
} else text1.append("2번째 체크 해제됨\n")
if (checkBox3.isChecked) {
text1.append("3번째 체크됨\n")
} else text1.append("3번째 체크 해제됨\n")
}
//checkBox1.setOnCheckedChangeListener(CheckboxListener())
checkBox2.setOnCheckedChangeListener(CheckboxListener())
//checkBox3.setOnCheckedChangeListener(CheckboxListener())
//람다식 방법
checkBox1.setOnCheckedChangeListener { buttonView, isChecked ->
Toast.makeText(this, isChecked.toString(), Toast.LENGTH_SHORT).show();
if (isChecked) text1.text = "1번째 체크됨"
else text1.text = "1번째 체크해제됨"
}
//람다식 방법
checkBox3.setOnCheckedChangeListener { _, isChecked ->
Toast.makeText(this, isChecked.toString(), Toast.LENGTH_SHORT).show();
if (isChecked) text1.text = "1번째 체크됨"
else text1.text = "1번째 체크해제됨"
}
}
inner class CheckboxListener : CompoundButton.OnCheckedChangeListener {
override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
when (buttonView?.id) {
R.id.checkBox1 ->
if (isChecked) text1.text = "1번째 체크됨"
else text1.text = "1번째 체크해제됨"
R.id.checkBox2 ->
if (isChecked) text1.text = "2번째 체크됨"
else text1.text = "2번째 체크해제됨"
R.id.checkBox3 ->
if (isChecked) text1.text = "3번째 체크됨"
else text1.text = "3번째 체크해제됨"
}
}
}
}
[activity_main.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello World!"
android:textAppearance="@style/TextAppearance.AppCompat.Display2" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CheckBox" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CheckBox" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CheckBox3" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="체크" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="체크해제" />
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="선택 반전" />
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="상태 확인" />
</LinearLayout>
[build.gradle(:app)]
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
defaultConfig {
applicationId "edu.kotlin.study"
minSdkVersion 22
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.1'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
[REFERENCE]
stackoverflow.com/questions/44150185/kotlin-android-how-implement-checkbox-oncheckedchangelistener

