APUNTES ANDROID
  • Introducción
  • Apuntes Linux
  • Apuntes Red Team
  • Apuntes Blue Team
  • Apuntes Python
  • Ricardev github
  • Escribiendo tu primera App
    • Instalar Android Studio
    • Proyecto
    • Ejecutar una App
    • Anatomía del Proyecto
      • Gradle scripts
      • AndroidManifest.xml
      • Java
      • Res
    • Componentes de una App
      • Activities
      • Fragments
      • Views y ViewGroups
      • Services
      • Broadcast Receivers
      • Intents
      • Content Provider
      • Widgets
    • Paradigmas de diseño
      • Views
        • Pallete Texts
          • TextView
          • EditText
          • AutoCompleteTextView
        • Pallete Buttons
          • Button
          • ImageButton
          • Chip y ChipGroup
          • RadioButton y RadioGroup
          • CheckBox
          • ToggleButton
          • Switch
          • FloatingActionButton
        • Pallete Widgets
          • ImageView
          • ShapeableImageView
          • WebView
          • VideoView
          • CalendarView
          • ProgressBar
          • SeekBar
          • RatingBar
          • SearchView
          • Divider
        • Custom Views
        • View Binding
      • Jetpack Compose
    • Layouts
      • FrameLayout
      • Linear Layout
      • Relative Layout
      • Constraint Layout
      • Table Layout
      • Grid Layout
    • Containers
      • Spinner
      • RecyclerView
      • CardView
      • ScrollView y HorizontalScrollView
      • ViewPager2
      • AppBarLayout y BottomAppBar
      • NavigationView y BottomNavigationView
      • Toolbar y MaterialToolbar
      • TabLayout y TabItem
      • ViewStub
      • etiquetas <include> y <merge>
Powered by GitBook
On this page
  • DEFINICIÓN
  • USO DESDE XML
  • ATRIBUTOS
  • android:disabledAlpha
  • android:textOff
  • android:textOn
  • PROGRAMAR EVENTOS EN CÓDIGO
  • PERSONALIZACIÓN
  • Lista de estados:
  • tb_ready_on
  • tb_ready_off
  • activity_main.xml
  1. Escribiendo tu primera App
  2. Paradigmas de diseño
  3. Views
  4. Pallete Buttons

ToggleButton

Explicación del concepto de ToggleButton

PreviousCheckBoxNextSwitch

Last updated 2 years ago

DEFINICIÓN

Hereda de:

Un botón que muestra el estado marcado (checked) y desmarcado (unchecked) con un indicador luminoso y por defecto el texto "ON" u "OFF".

USO DESDE XML

<ToggleButton
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
<ToggleButton
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:checked="true"/>

ATRIBUTOS

android:disabledAlpha

Define el valor de transparencia del ToggleButton cuando se encuentra deshabilitado. Debe ser un valor de coma flotante entre 0.0 (completamente transparente) y 1.0 (completamente visible).

android:textOff

Define el texto que se muestra en el ToggleButton cuando está en estado desmarcado.

android:textOn

Define el texto que se muestra en el ToggleButton cuando está en estado marcado.

PROGRAMAR EVENTOS EN CÓDIGO

La programación de eventos para los CheckBox no tiene ninguna dificultad con respecto a los que hemos visto anteriormente por lo que solamente vamos a ver el código:

MainActivity.kt
package com.example.android.appdeejemplo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import android.widget.ToggleButton

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val tbReady: ToggleButton = findViewById(R.id.tbReady)
        tbReady.setOnCheckedChangeListener{_, isChecked ->
            if (isChecked) Toast.makeText(this, "¡Estamos listos! Comenzamos...", 
            Toast.LENGTH_SHORT).show()
            else Toast.makeText(this, "Vamos a descansar un rato...", 
            Toast.LENGTH_SHORT).show()
        }
    }
}
<ToggleButton
    android:id="@+id/tbReady"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textOn="Estoy listo"
    android:textOff="Vamos a descansar..."/>

PERSONALIZACIÓN

Como pueden ver, el ToggleButton tiene un diseño muy concreto, además de no muy atractivo.

En este apartado vamos a ver una opción de personalización que permite modificar el botón al completo. Esto lo vamos a hacer con conocimientos que ya hemos adquirido a lo largo del curso.

Lista de estados:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:enterFadeDuration="@android:integer/config_shortAnimTime"
    android:exitFadeDuration="@android:integer/config_shortAnimTime">

    <item android:drawable="@drawable/tb_ready_on" android:state_checked="true" />
    <item android:drawable="@drawable/tb_ready_off" android:state_checked="false" />
</selector>

Como vemos, se pueden añadir animaciones para hacer el cambio más suave.

tb_ready_on

En este caso, no son imagenes vectoriales sino simples imagenes en formato png:

tb_ready_off

activity_main.xml

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="30dp"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pulse el botón cuando se sienta preparado:"
        android:paddingBottom="30dp"/>

    <ToggleButton
        android:id="@+id/tbReady"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/tb_ready_bg"
        android:textOn="@null"
        android:textOff="@null"/>
</LinearLayout>

Herencia ToggleButton
tb_ready_on
tb_ready_off
ToggleButton  |  Android DevelopersAndroid Developers
Fuente: developer.android
Logo