본문 바로가기
안드로이드/Widget

안드로이드 Switch

by 김어찐 2022. 5. 30.
728x90

ON/OFF 상태를 좌우로 이동하면서 설정할 수 있는 View 이다

 

주요 속성

text : Switch 좌측에 표시되는 문자열을 설정한다.
thumb : 버튼 부분의 이미지를 설정한다.
track : 트랙 부분의 이미지를 설정한다.
textOn : on 상태일 때 표시되는 문자열을 설정한다.
textOff : off 상태일 때 표시되는 문자열을 설정한다.
showText : textOn, textOff에 설정한 문자열을 보여줄 것인가를 설정한다.
checked : ON/OFF 상태를 설정한다.

 

주요 프로퍼티

isChecked : Switch의 ON/OFF 상태 값. 

 

주요 이벤트

checkedChange : Switch의 ON/OFF 상태가 변경되었을 때.

 

package com.example.aswitch

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.CompoundButton
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.math.log

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener {
            if (switch1.isChecked == true) {
                textView.text = "ON 상태 입니다"
            } else {
                textView.text = "OFF 상태 입니다"
            }
        }

        button2.setOnClickListener {
            switch1.isChecked=true
        }

        button3.setOnClickListener {
            switch1.isChecked=false
        }

        switch1.setOnCheckedChangeListener(listener1)
        switch2.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked == true) {
                textView2.text = "두 번째 스위치가 ON"
            } else {
                textView2.text="두 번째 스위치가 OFF"
            }
        }
    }

    val listener1 = object : CompoundButton.OnCheckedChangeListener{
        override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
            when (buttonView?.id) {
                R.id.switch1 -> {
                    if (isChecked == true) {
                        textView.text = "첫 번째 스위치가 ON 상태가 되었습니다"
                    } else {
                        textView.text = "첫 번째 스위치가 OFF 상태가 되었습니다"
                    }
                }
            }
        }
    }


}

728x90

'안드로이드 > Widget' 카테고리의 다른 글

안드로이드 Chip  (0) 2022.05.31
안드로이드 CheckedTextView  (0) 2022.05.31
안드로이드 RadioButton  (0) 2022.05.30
안드로이드 CheckBox  (0) 2022.05.30
안드로이드 ToggleButton  (0) 2022.05.30