전환 버튼 추가

Compose 방법 사용해 보기
Jetpack Compose는 Android에 권장되는 UI 도구 키트입니다. Compose에서 구성요소를 추가하는 방법을 알아봅니다.

View 기반 레이아웃을 사용하고 있다면 기본 3가지 방법으로 전환 버튼을 구현할 수 있습니다. Material 구성요소 라이브러리의 SwitchMaterial 구성요소를 사용하는 것이 좋습니다.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <com.google.android.material.switchmaterial.SwitchMaterial
        android:id="@+id/material_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/material_switch"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

다음 예와 같이 기존 앱은 여전히 이전 SwitchCompat AppCompat 구성요소를 사용할 수 있습니다.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <androidx.appcompat.widget.SwitchCompat
        android:id="@+id/switchcompat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/switchcompat"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

다음 예는 UI가 눈에 띄게 다른 또 다른 기존 구성요소인 AppCompatToggleButton를 보여줍니다.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <TextView
        android:id="@+id/toggle_button_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@id/toggle"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintBaseline_toBaselineOf="@id/toggle"
        android:text="@string/toggle_button" />

    <androidx.appcompat.widget.AppCompatToggleButton
        android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/toggle_button_label"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

이 3가지 구성요소는 동일한 동작을 제공하지만 모양은 다릅니다. SwitchMaterialSwitchCompat의 차이는 미미하지만 AppCompatToggleButton는 눈에 띄게 다릅니다.

SwitchMaterial, SwitchCompat, AppCompatToggleButton 컨트롤

그림 1. 세 가지 전환 버튼 유형

상태 변경 처리

SwitchMaterial, SwitchCompat, AppCompatToggleButton는 모두 CompoundButton의 서브클래스로, 확인된 상태 변경을 처리하는 공통 메커니즘을 제공합니다. 다음 예와 같이 CompoundButton.OnCheckedChangeListener 인스턴스를 구현하여 버튼에 추가합니다.

Kotlin

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val binding: SwitchLayoutBinding = SwitchLayoutBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.materialSwitch.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                // The switch is checked.
            } else {
                // The switch isn't checked.
            }
        }
    }
}

Java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SwitchLayoutBinding binding = SwitchLayoutBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.materialSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // The switch is checked.
            } else {
                // The switch isn't checked.
            }
        });
    }
}

CompoundButton.OnCheckedChangeListener는 단일 추상 메서드 인터페이스(또는 SAM 인터페이스)이므로 람다로 구현할 수 있습니다. 확인된 상태가 변경될 때마다 람다가 호출되며 람다에 전달된 isChecked 불리언 값은 새로 선택된 상태를 나타냅니다.