Temas de botones de acción flotantes en Android con ejemplo

Requisito previo:

Los desarrolladores de aplicaciones de Android quieren llamar la atención de los usuarios al personalizar y tematizar los widgets de la aplicación de Android y mantener más tráfico de clientes solo por el diseño de la aplicación. En este artículo, se ha discutido la tematización de uno de los elementos de interfaz de usuario más importantes que son los botones de acción flotantes (extendidos y normales). A continuación, se muestran algunas imágenes de muestra de botones de acción flotantes de tematización.

Theming Floating Action Buttons in Android with Example

Pasos para crear botones de acción flotantes temáticos

Paso 1: Cree un proyecto de Android Studio de actividad vacía

Paso 2: agregue una dependencia al archivo Gradle de nivel de aplicación.

  • Aquí estamos utilizando el botón de acción flotante que está diseñado y desarrollado por el equipo de diseño de materiales de Google.
  • Agregue la dependencia en el archivo build.gradle(app) como:

implementación ‘com.google.android.material:material:1.3.0-alpha02’

  • Asegúrese de agregar la dependencia al archivo Gradle del nivel de la aplicación. Después de agregar la dependencia, debe hacer clic en el botón «Sincronizar ahora» que aparece en la esquina superior derecha del IDE de Android Studio.
  • Cuando haga clic en el botón Sincronizar ahora, asegúrese de estar conectado a la red para que pueda descargar los archivos necesarios.
  • Consulte la imagen a continuación si no puede obtener los pasos mencionados anteriormente o si no puede ubicar el archivo Gradle del nivel de la aplicación:

Gradle File

Paso 3: Cambie el tema base de la aplicación en el archivo styles.xml

  • El tema debe cambiarse ya que el botón de acción ExtendedFloating es la clase secundaria de los botones de diseño de materiales de Google. Por lo tanto, necesita que el tema MaterialComponent se aplique al tema Base de la aplicación. De lo contrario, la aplicación se bloqueará inmediatamente tan pronto como iniciemos la aplicación.
  • Puede consultar este artículo: Botones de diseño de materiales en Android con ejemplo , ya que el botón de diseño de material extendido es una clase secundaria de los botones de diseño de materiales. El artículo dice las ventajas de tener botones de diseño de materiales y por qué es necesario cambiar el tema.
  • Vaya a aplicación -> src -> principal -> res -> valores -> estilos.xml y cambie el tema base de la aplicación. MaterialComponents contiene varios estilos de tema de barra de acción, uno puede invocar cualquiera de los estilos de tema de barra de acción de MaterialComponents , excepto los estilos AppCompat . A continuación se muestra el código para el archivo styles.xml .

XML

<resources> 
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> 
        <!-- Customize your theme here -->
        <item name="colorPrimary">@color/colorPrimary</item> 
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item> 
        <item name="colorAccent">@color/colorAccent</item> 
    </style> 
</resources> 

Si no puede obtener las cosas en el paso mencionado anteriormente, puede consultar esta imagen.

Paso 4: importa algunos de los íconos vectoriales en la carpeta dibujable

  • En este caso, se importan iconos simples de agregar vector, agregar alarma, vector, agregar vector de persona con fines de demostración.
  • Para importar cualquier vector en el proyecto, es necesario hacer clic con el botón derecho en la carpeta dibujable -> Nuevo -> Vector activo.
  • Se abrirá una nueva ventana emergente y elija cualquier vector que desee haciendo clic en el botón Clip Art .
  • Puede consultar la siguiente imagen para saber cómo abrir el selector de activos vectoriales.

Vector Asset

  • Puede consultar la siguiente imagen para saber cómo ubicar el botón Clip Art y elegir los vectores.

Clip art

Paso 5: trabajar con el archivo activity_main.xml

  • Ahora, en el archivo activity_main.xml , agregue un botón de acción flotante normal y un botón de acción flotante extendido. Asegúrate de usar ConstraintLayout .
  • Invoque ambos botones de acción flotante, de modo que se pueda ver cómo cambian estos dos botones después de manipular el archivo styles.xml .
  • Invoque el siguiente código para agregar ambos botones de acción flotantes:

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"
    tools:ignore="HardcodedText">
  
    <!--Google material normal Floating Action Button-->
    <!--one needs to keep the margin of 16dp from the screen to button-->
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginBottom="16dp"
        android:src="@drawable/ic_add_black_24dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
  
    <!--Google material Extended Floating Action Button-->
    <!--one needs to keep the margin of 16dp from the screen to button-->
    <com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        android:text="Actions"
        app:icon="@drawable/ic_add_black_24dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
  
</androidx.constraintlayout.widget.ConstraintLayout>

Después de invocar el código, se produce la siguiente interfaz de usuario:

Output UI

  • Para cambiar el color de fondo de ambos FAB, invoque el siguiente atributo mientras define estos dos FAB en el archivo activity_main.xml (agregue backgroundTint manualmente porque todos los FAB se aplicarán con el tema predeterminado de SmallComponent).

android:backgroundTint=”@color/colorAccent”

Ahora analicemos cómo cambiar el tema de los dos botones de acción flotantes en un solo código: 

  • Para cambiar el tema de ambos FAB, debemos anular el tema predeterminado que es el tema SmallComponent en el archivo styles.xml

XML

<resources>
  
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <!--to do the changes in the corner, the cornerFamily 
            attribute is the part of the SmallComponent-->
        <!--so we need to override the shapeAppearanceSmallComponent-->
        <!--which is the default theme applied for all of the 
            Google MDC buttons it may be FAB or MDC Buttons-->
        <item name="shapeAppearanceSmallComponent">@style/ShapeAppearance.App.SmallComponent</item>
    </style>
  
    <style name="ShapeAppearance.App.SmallComponent" parent="ShapeAppearance.MaterialComponents.SmallComponent">
        <item name="cornerFamily">cut</item>
    </style>
  
</resources>

Salida: Ejecutar en Emulator (después de realizar cambios en styles.xml): 

  • Se puede observar que en el código anterior, el atributo » cornerFamily» se invoca como valor de » corte» . Así que anulemos la familia de esquinas del tema SmallComponent.
  • El atributo “ cornerFamily” contiene los dos valores que son “ corte” y “ redondeado”. Para obtener más información sobre estos, continúe leyendo el artículo sobre cómo cambiar el tamaño de la esquina con la ayuda del atributo » cornerSize» .
  • Entonces, este método de cambiar el tema afecta a todos los tipos de FAB, ya sea un FAB extendido o normal.
  • Incluso cambia la forma y el tema de los botones de Google Material Design si están implementados en la aplicación. Consulte esto: Botones de diseño de materiales en Android con ejemplo .

Ahora analicemos cómo cambiar por separado el tema de ambos tipos de FAB: 

  • Ahora, en el mismo archivo styles.xml , necesitamos hacer pequeños cambios.
  • En el caso anterior, hemos invocado el elemento “ shapeAppearanceSmallComponent ” dentro del estilo AppTheme.
  • Ahora necesitamos agregar los elementos » extendedFloatingActionButtonStyle» para FAB extendido y » floatingActionButtonStyle» para FAB normal, para diferenciar la temática de ambos.
  • Consulte el siguiente código sobre cómo se ha hecho: 

XML

<resources>
  
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
            
        <!--this attribute is to change the theme of the extended FAB-->
        <item name="extendedFloatingActionButtonStyle">
            @style/Widget.App.ExtendedFloatingActionButton</item>
  
        <!--this attribute is to change the theme of the normal FAB-->
        <item name="floatingActionButtonStyle">@style/Widget.App.FloatingActionButton</item>
  
    </style>
    <!--changing the theme of the base application ends here-->
  
    <!--Now changing theme of extended FAB begins from here-->
    <!--make sure to change the value of the parent as 
        Widget.MaterialComponents.ExtendedFloatingActionButton-->
    <!--as we are only changing the theme of the extended FAB-->
  
    <!--inside Widget.App.ExtendedFloatingActionButton there are two attribute-->
    <!--which are making the change of the theme of the extended FAB-->
    <!--those are materialThemeOverlay and shapeAppearanceOverlay-->
    <style name="Widget.App.ExtendedFloatingActionButton" parent="Widget.MaterialComponents.ExtendedFloatingActionButton">
  
        <!--the following attribute will changes in the appearance 
            of the extended FAB in terms of colors-->
        <item name="materialThemeOverlay">@style/myCustomThemeForExtendedFab</item>
  
        <!--the following attribute will change in the 
            shape appearance of the extended FAB-->
        <item name="shapeAppearanceOverlay">@style/customExtendedFAB</item>
  
        <!--to make the code look cleaner and readable, the above 
            two children are implemented separately-->
    </style>
  
    <!--this style is the child of the shapeAppearanceOverlay attribute 
        which in turn is the child of materialThemeOverlay-->
    <style name="customExtendedFAB">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="cornerFamily">cut</item>
  
        <!--and the cornerSize makes the cut for all 4 corners of the FAB as 10dp-->
        <item name="cornerSize">10dp</item>
  
    </style>
  
    <!--Here no need of mentioning the parent-->
    <!--because this is already the child of the 
        shapeAppearanceOverlay which in turn is the child-->
    <!--of the Widget.App.ExtendedFloatingActionButton-->
    <style name="myCustomThemeForExtendedFab" parent="">
  
        <!--this attribute gives makes the change in the background of the FAB-->
        <item name="colorSecondary">@color/colorPrimary</item>
  
        <!--this attribute gives makes the change in the text and icon color of the FAB-->
        <item name="colorOnSecondary">@android:color/white</item>
          
    </style>
    <!--Changing the theme of the extended FAB completes here-->
  
    <!--Now changing theme of normal FAB begins from here-->
    <!--make sure to change the value of the parent as 
        Widget.MaterialComponents.FloatingActionButton-->
    <!--as we are only changing the theme of the normal FAB-->
  
    <!--inside Widget.App.FloatingActionButton there are two attribute-->
    <!--which are making the change of the theme of the normal FAB-->
    <!--those are materialThemeOverlay and shapeAppearanceOverlay-->
    <style name="Widget.App.FloatingActionButton" parent="Widget.MaterialComponents.FloatingActionButton">
  
        <!--the following attribute will changes in the appearance of 
            the normal FAB in terms of colors-->
        <item name="materialThemeOverlay">@style/myCustomThemeForNormalFab</item>
  
        <!--the following attribute will change in the shape appearance of the normal FAB-->
        <item name="shapeAppearanceOverlay">@style/customNormalFAB</item>
  
        <!--to make the code look cleaner and readable, the above 
            two children are implemented separately-->
    </style>
  
    <style name="customNormalFAB">
  
        <!--for the normal FAB the cornerFamily is given the value as the rounded-->
        <!--in this case it has been done to differentiate the 
            themes of the normal FAB and extended FAB-->
        <item name="cornerFamily">rounded</item>
  
        <!--and the cornerSize makes rounded corner for all
            4 corners of the FAB as 20dp radius-->
        <item name="cornerSize">20dp</item>
          
    </style>
  
    <style name="myCustomThemeForNormalFab" parent="">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="colorSecondary">@android:color/holo_green_dark</item>
  
        <!--this attribute gives makes the change in the text and icon color of the FAB-->
        <item name="colorOnSecondary">@android:color/white</item>
          
    </style>
    <!--Changing the theme of the normal FAB completes here-->
  
</resources>

Después de realizar cambios en el archivo styles.xml, se produce la siguiente interfaz de usuario:

Output UI

  • Ahora se establecen diferentes temas por separado para el FAB normal y el FAB extendido.

Nota: Los colores de ambos FAB se hacen diferentes en este caso, solo con fines de demostración, ya que esto no se recomienda, los colores de todos los FAB deben ser iguales para toda la aplicación de acuerdo con las recomendaciones de diseño de materiales.

Experimente con customNormalFAB y customExtendedFAB 

  • Ahora experimente con los elementos secundarios » customNormalFAB » y » customExtendedFAB » (y el resto de las cosas no cambiaron) para realizar cambios en las formas de ambos FAB.
  • Experimente también con “ cornerSizeTopRight”, “cornerSizeTopLeft”, “cornerSizeBottomRight” y “ cornerSizeBottomLeft”.
  • Ahora haga cambios en ambos niños de la siguiente manera: 

Ejemplo 1: 

XML

<!--for Extended FAB-->
<style name="customExtendedFAB">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="cornerFamily">cut</item>
        <!--this attribute will make changes to Top Right according to value-->
        <item name="cornerSizeTopRight">0dp</item>
        <!--this attribute will make changes to Top Left according to value-->
        <item name="cornerSizeTopLeft">0dp</item>
        <!--this attribute will make changes to Bottom Right according to value-->
        <item name="cornerSizeBottomRight">0dp</item>
        <!--this attribute will make changes to Bottom Left according to value-->
        <item name="cornerSizeBottomLeft">0dp</item>
  
</style>
  
<!--for Normal FAB-->
<style name="customNormalFAB">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="cornerFamily">cut</item>
        <!--this attribute will make changes to Top Right according to value-->
        <item name="cornerSizeTopRight">0dp</item>
        <!--this attribute will make changes to Top Left according to value-->
        <item name="cornerSizeTopLeft">0dp</item>
        <!--this attribute will make changes to Bottom Right according to value-->
        <item name="cornerSizeBottomRight">0dp</item>
        <!--this attribute will make changes to Bottom Left according to value-->
        <item name="cornerSizeBottomLeft">0dp</item>
  
</style>

La interfaz de usuario de salida será: 

Theming Floating Action Buttons in Android with Example

Ejemplo 2:

XML

<!--for Extended FAB-->
<style name="customExtendedFAB">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="cornerFamily">cut</item>
        <!--this attribute will make changes to Top Right according to value-->
        <item name="cornerSizeTopRight">0dp</item>
        <!--this attribute will make changes to Top Left according to value-->
        <item name="cornerSizeTopLeft">14dp</item>
        <!--this attribute will make changes to Bottom Right according to value-->
        <item name="cornerSizeBottomRight">14dp</item>
        <!--this attribute will make changes to Bottom Left according to value-->
        <item name="cornerSizeBottomLeft">0dp</item>
  
</style>
  
<!--for Normal FAB-->
<style name="customNormalFAB">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="cornerFamily">cut</item>
        <!--this attribute will make changes to Top Right according to value-->
        <item name="cornerSizeTopRight">0dp</item>
        <!--this attribute will make changes to Top Left according to value-->
        <item name="cornerSizeTopLeft">14dp</item>
        <!--this attribute will make changes to Bottom Right according to value-->
        <item name="cornerSizeBottomRight">14dp</item>
        <!--this attribute will make changes to Bottom Left according to value-->
        <item name="cornerSizeBottomLeft">0dp</item>
  
</style>

La interfaz de usuario de salida será:

Theming Floating Action Buttons in Android with Example

Ejemplo 3:

XML

<!--for Extended FAB-->
<style name="customExtendedFAB">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="cornerFamily">cut</item>
        <!--this attribute will make changes to Top Right according to value-->
        <item name="cornerSizeTopRight">0dp</item>
        <!--this attribute will make changes to Top Left according to value-->
        <item name="cornerSizeTopLeft">0dp</item>
        <!--this attribute will make changes to Bottom Right according to value-->
        <item name="cornerSizeBottomRight">14dp</item>
        <!--this attribute will make changes to Bottom Left according to value-->
        <item name="cornerSizeBottomLeft">14dp</item>
  
</style>
  
<!--for Normal FAB-->
<style name="customNormalFAB">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="cornerFamily">cut</item>
        <!--this attribute will make changes to Top Right according to value-->
        <item name="cornerSizeTopRight">0dp</item>
        <!--this attribute will make changes to Top Left according to value-->
        <item name="cornerSizeTopLeft">0dp</item>
        <!--this attribute will make changes to Bottom Right according to value-->
        <item name="cornerSizeBottomRight">14dp</item>
        <!--this attribute will make changes to Bottom Left according to value-->
        <item name="cornerSizeBottomLeft">14dp</item>
  
</style>

La interfaz de usuario de salida será:

Theming Floating Action Buttons in Android with Example

Ejemplo 4:

XML

<!--for Extended FAB-->
<style name="customExtendedFAB">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="cornerFamily">rounded</item>
        <!--this attribute will make changes to Top Right according to value-->
        <item name="cornerSizeTopRight">0dp</item>
        <!--this attribute will make changes to Top Left according to value-->
        <item name="cornerSizeTopLeft">14dp</item>
        <!--this attribute will make changes to Bottom Right according to value-->
        <item name="cornerSizeBottomRight">14dp</item>
        <!--this attribute will make changes to Bottom Left according to value-->
        <item name="cornerSizeBottomLeft">0dp</item>
  
</style>
  
<!--for Normal FAB-->
<style name="customNormalFAB">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="cornerFamily">rounded</item>
        <!--this attribute will make changes to Top Right according to value-->
        <item name="cornerSizeTopRight">0dp</item>
        <!--this attribute will make changes to Top Left according to value-->
        <item name="cornerSizeTopLeft">14dp</item>
        <!--this attribute will make changes to Bottom Right according to value-->
        <item name="cornerSizeBottomRight">14dp</item>
        <!--this attribute will make changes to Bottom Left according to value-->
        <item name="cornerSizeBottomLeft">0dp</item>
  
</style>

La interfaz de usuario de salida será:

Theming Floating Action Buttons in Android with Example

Ejemplo 5:

XML

<!--for Extended FAB-->
<style name="customExtendedFAB">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="cornerFamily">rounded</item>
        <!--this attribute will make changes to Top Right according to value-->
        <item name="cornerSizeTopRight">14dp</item>
        <!--this attribute will make changes to Top Left according to value-->
        <item name="cornerSizeTopLeft">14dp</item>
        <!--this attribute will make changes to Bottom Right according to value-->
        <item name="cornerSizeBottomRight">0dp</item>
        <!--this attribute will make changes to Bottom Left according to value-->
        <item name="cornerSizeBottomLeft">0dp</item>
  
</style>
  
<!--for Normal FAB-->
<style name="customNormalFAB">
  
        <!--for the extended FAB the cornerFamily is given the value as the cut-->
        <item name="cornerFamily">rounded</item>
        <!--this attribute will make changes to Top Right according to value-->
        <item name="cornerSizeTopRight">14dp</item>
        <!--this attribute will make changes to Top Left according to value-->
        <item name="cornerSizeTopLeft">14dp</item>
        <!--this attribute will make changes to Bottom Right according to value-->
        <item name="cornerSizeBottomRight">0dp</item>
        <!--this attribute will make changes to Bottom Left according to value-->
        <item name="cornerSizeBottomLeft">0dp</item>
  
</style>

La interfaz de usuario de salida será:

Theming Floating Action Buttons in Android with Example

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *