개발(Android)/android studio

[Android Studio/Kotlin] Buttons (1) Switch, Toggle Button, Check Box

shinyelee 2022. 5. 4. 16:02

[안드로이드 스튜디오/코틀린] 스위치, 토글 버튼, 체크 박스

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

package com.shinyelee.android_study2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.shinyelee.android_study2.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private var vBinding : ActivityMainBinding? = null
    private val binding get() = vBinding!!

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        vBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

    }

    override fun onDestroy() {
        vBinding = null
        super.onDestroy()
    }

}

Switch

<!-- ConstraintLayout 하위 -->
    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
// override fun onCreate 하위
        binding.switch1.setOnCheckedChangeListener { compoundButton, b ->
            println(b)
        }
        binding.switch1.isChecked = true

스위치를 클릭해
on/off 설정이 가능함


ToggleButton

    <ToggleButton
        android:id="@+id/toggleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToggleButton"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
        binding.toggleButton.setOnCheckedChangeListener { compoundButton, b ->
            println(b)
        }
        binding.toggleButton.isChecked = true


CheckBox

    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="CheckBox"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
        binding.checkBox.setOnCheckedChangeListener { compoundButton, b ->
            println(b)
        }
        binding.checkBox.isChecked = true


참고

반응형