전환 버튼 추가
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Compose 사용해 보기
Jetpack Compose는 Android를 위한 권장 UI 도구 키트입니다. Compose에서 구성요소를 추가하는 방법을 알아보세요.
View
기반 레이아웃을 사용하는 경우 전환을 구현하는 데는 세 가지 기본 옵션이 있습니다. 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>
이 세 가지 구성요소는 동일한 동작을 제공하지만 모양이 다릅니다. SwitchMaterial
와 SwitchCompat
의 차이는 미묘하지만 AppCompatToggleButton
는 눈에 띄게 다릅니다.
그림 1. 전환 버튼 유형 3가지
상태 변경 처리
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.
}
}
}
}
자바
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
불리언 값은 새 선택된 상태를 나타냅니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-27(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-07-27(UTC)"],[],[],null,["# Add toggle buttons\n\nTry the Compose way \nJetpack Compose is the recommended UI toolkit for Android. Learn how to add components in Compose. \n[Switch →](/develop/ui/compose/components/switch) \n\n\u003cbr /\u003e\n\nIf you're using a `View`-based layout, there are three main choices for\nimplementing toggles. We recommend using the\n[`SwitchMaterial`](https://m3.material.io/components/switch/overview) component\nfrom the [Material\nComponents](https://m3.material.io/develop/android/mdc-android) library: \n\n \u003candroidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16dp\"\u003e\n\n \u003ccom.google.android.material.switchmaterial.SwitchMaterial\n android:id=\"@+id/material_switch\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/material_switch\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" /\u003e\n\n \u003c/androidx.constraintlayout.widget.ConstraintLayout\u003e\n\nLegacy apps might still use the older\n[`SwitchCompat`](/reference/androidx/appcompat/widget/SwitchCompat) AppCompat\ncomponent, as shown in the following example: \n\n \u003candroidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16dp\"\u003e\n\n \u003candroidx.appcompat.widget.SwitchCompat\n android:id=\"@+id/switchcompat\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/switchcompat\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" /\u003e\n\n \u003c/androidx.constraintlayout.widget.ConstraintLayout\u003e\n\nThe following example shows\n[`AppCompatToggleButton`](/reference/androidx/appcompat/widget/AppCompatToggleButton),\nwhich is another legacy component that has a noticeably different UI: \n\n \u003candroidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16dp\"\u003e\n\n \u003cTextView\n android:id=\"@+id/toggle_button_label\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n app:layout_constraintStart_toStartOf=\"parent\"\n app:layout_constraintEnd_toStartOf=\"@id/toggle\"\n app:layout_constraintHorizontal_chainStyle=\"packed\"\n app:layout_constraintBaseline_toBaselineOf=\"@id/toggle\"\n android:text=\"@string/toggle_button\" /\u003e\n\n \u003candroidx.appcompat.widget.AppCompatToggleButton\n android:id=\"@+id/toggle\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintStart_toEndOf=\"@id/toggle_button_label\"\n app:layout_constraintTop_toTopOf=\"parent\"\n app:layout_constraintBottom_toBottomOf=\"parent\"/\u003e\n\n \u003c/androidx.constraintlayout.widget.ConstraintLayout\u003e\n\nThese three components offer the same behavior but look different. The\ndifferences between the `SwitchMaterial` and `SwitchCompat` are subtle, but\n`AppCompatToggleButton` is noticeably different:\n\n\n**Figure 1.** Three toggle button types.\n\n\u003cbr /\u003e\n\n### Handle state changes\n\n`SwitchMaterial`, `SwitchCompat`, and `AppCompatToggleButton` are all subclasses\nof [`CompoundButton`](/reference/android/widget/CompoundButton), which\ngives them a common mechanism for handling checked state changes. You implement\nan instance of\n[`CompoundButton.OnCheckedChangeListener`](/reference/android/widget/CompoundButton.OnCheckedChangeListener)\nand add it to the button, as shown in the following example: \n\n### Kotlin\n\n```kotlin\nclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n\n val binding: SwitchLayoutBinding = SwitchLayoutBinding.inflate(layoutInflater)\n setContentView(binding.root)\n\n binding.materialSwitch.setOnCheckedChangeListener { _, isChecked -\u003e\n if (isChecked) {\n // The switch is checked.\n } else {\n // The switch isn't checked.\n }\n }\n }\n}\n```\n\n### Java\n\n```java\npublic class MainActivity extends AppCompatActivity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n SwitchLayoutBinding binding = SwitchLayoutBinding.inflate(getLayoutInflater());\n setContentView(binding.getRoot());\n\n binding.materialSwitch.setOnCheckedChangeListener((buttonView, isChecked) -\u003e {\n if (isChecked) {\n // The switch is checked.\n } else {\n // The switch isn't checked.\n }\n });\n }\n}\n```\n\n`CompoundButton.OnCheckedChangeListener` is a single abstract method interface\n(or *SAM interface* ), so you can implement it as a lambda. The lambda is called\nwhenever the checked state changes, and the value of the `isChecked` boolean\nthat is passed to the lambda indicates the new checked state."]]