Adicionar botões de ativação

Teste o Compose
O Jetpack Compose é o kit de ferramentas de interface recomendado para Android. Aprenda a adicionar componentes no Compose.

Se você estiver usando um layout baseado em View, há três opções principais para implementar botões de alternância. Recomendamos o uso do componente SwitchMaterial da biblioteca Componentes do Material Design:

<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>

Os apps legados ainda podem usar o componente SwitchCompat AppCompat antigo, conforme mostrado no exemplo abaixo:

<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>

O exemplo abaixo mostra AppCompatToggleButton, que é outro componente legado com uma interface visivelmente diferente:

<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>

Esses três componentes oferecem o mesmo comportamento, mas têm aparência diferente. As diferenças entre SwitchMaterial e SwitchCompat são sutis, mas AppCompatToggleButton é visivelmente diferente:

Os controles SwitchMaterial, SwitchCompat e AppCompatToggleButton

Figura 1. Três tipos de botão ativar.

Gerenciar mudanças de estado

SwitchMaterial, SwitchCompat e AppCompatToggleButton são subclasses de CompoundButton, o que fornece a eles um mecanismo comum para processar mudanças de estado verificadas. Implemente uma instância de CompoundButton.OnCheckedChangeListener e a adicione ao botão, como mostrado no exemplo a seguir:

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 é uma única interface de método abstrato (ou interface SAM), para que você possa implementá-la como um lambda. A lambda é chamada sempre que o estado marcado muda, e o valor do booleano isChecked que é transmitido à lambda indica o novo estado marcado.