DBILITY

안드로이드 checkbox,toggle,switch 간단 사용법 본문

android

안드로이드 checkbox,toggle,switch 간단 사용법

DBILITY 2024. 2. 28. 15:52
반응형

package com.example.myex01

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.CheckBox
import androidx.core.view.children
import androidx.core.widget.addTextChangedListener
import com.example.myex01.databinding.ActivityMain3Binding

class MainActivity3 : AppCompatActivity() {

    private lateinit var binding: ActivityMain3Binding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMain3Binding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.run {
            
            for (checkBox in linearLayout.children) {
                if (checkBox is CheckBox) {
                    checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
                        when (buttonView.id) {
                            R.id.checkApple -> {
                                Log.d(
                                    "setOnCheckedChangeListener",
                                    buttonView.text.toString() + ":" + isChecked.toString()
                                )
                            }

                            R.id.checkBanana -> {
                                Log.d(
                                    "setOnCheckedChangeListener",
                                    buttonView.text.toString() + ":" + isChecked.toString()
                                )
                            }

                            R.id.checkOrange -> {
                                Log.d(
                                    "setOnCheckedChangeListener",
                                    buttonView.text.toString() + ":" + isChecked.toString()
                                )
                            }
                        }
                    }
                }
            }

            toggleButton.setOnCheckedChangeListener { _, isChecked ->
                textToggle.text = if (isChecked) "On" else "Off"
            }

            switchButton.setOnCheckedChangeListener { _, isChecked ->
                textSwitch.text = if (isChecked) "On" else "Off"
            }
        }
    }
}

반응형
Comments