안드로이드(Kotlin)/기초/

CheckBox, RadioButton 사용법

2020. 4. 22.

컴포넌트 트리

RadioGroup -> id: colorGruop

RadioButton1 -> id: redOpt

RadioButton2 -> id: blueOpt

LinearLayout

CheckBox1 -> id: boldOpt

CheckBox2 -> id: italicOpt

 

코드

package com.example.myexam1

import android.graphics.Color
import android.graphics.Typeface.BOLD
import android.graphics.Typeface.ITALIC
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.CompoundButton
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), CompoundButton.OnCheckedChangeListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        boldOpt.setOnCheckedChangeListener(this)
        italicOpt.setOnCheckedChangeListener(this)

        colorGroup.setOnCheckedChangeListener { _, checkedId ->
            when(checkedId){
                R.id.blueOpt -> textView.setTextColor(Color.BLUE)
                R.id.redOpt -> textView.setTextColor(Color.RED)
            }
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        var opt = 0

        if(boldOpt.isChecked) opt += BOLD
        if(italicOpt.isChecked) opt += ITALIC

        textView.setTypeface(null, opt)
    }
}