Hola, chicos. En los próximos videos, aprenderemos cómo implementar un cajón de navegación en nuestra aplicación con el que podemos cambiar entre diferentes fragmentos. Construiremos este cajón de navegación desde cero y lo dividiremos en 3 partes diferentes porque hay bastantes pasos necesarios. En la primera parte, haremos algunos preparativos. cuadro debajo de cada video encontrará el enlace al código para este ejemplo Y lanzaré las partes restantes en los próximos días Bien, comencemos Primero, tenemos que agregar la dependencia para la biblioteca de soporte de diseño Porque contiene el cajón de navegación Así que vamos a nuestro archivo build.gradle con "(Módulo: aplicación)" en su nombre Y aquí en la parte inferior, agregamos esta dependencia Para esto, copiamos esta dependencia "appcompat" completamente con la parte "implementación" compat-v7" a "diseño" Asegúrese de cambiar "v7" y "diseño" Mantenemos el número de versión igual que tenemos aquí Y cuando hemos agregado esto, hacemos clic en "Sincronizar ahora" Espere un momento Y cuando haya terminado de sincronizar, estamos listos para comenzar Ahora Android Studio también ofrece una actividad de cajón de navegación lista para usar, que puede encontrar cuando hace clic con el botón derecho en su paquete Vaya a "Nuevo" -> "Actividad" y aquí puede encontrar "Actividad del cajón de navegación" Cuando haga clic en esto, obtendrá una actividad completa con el cajón de navegación y todo el código necesario y se verá bastante similar al que vamos a construir Pero este cajón de navegación no abrirá fragmentos Y también, si no sabe lo que hace cada uno de los archivos, puede ser muy confuso, así que es mejor aprenderlo construyéndolo desde cero Así que omitiremos esto E implementar esto en nuestra actividad vacía Primero comenzamos con nuestros íconos Así que abrimos nuestra carpeta "res" aquí abrimos "drawable" y hacemos clic derecho en "drawable" vamos a "Nuevo" y aquí hacemos clic en "Vector Asset Luego se abre esta ventana y aquí hacemos clic en este ícono Y luego podemos elegir entre muchos íconos diferentes Y puedes elegir los íconos que quieras Voy a elegir el mismo que tenía en el ejemplo El primero fue este ícono de correo aquí Está bien Y cambiaré ligeramente el nombre a "ic_message" Porque esto es lo que dirá el elemento del menú en nuestro cajón de navegación Haga clic en "Siguiente" Y aquí en "Finalizar" Y ahora encontramos nuestro ícono en esta carpeta "dibujable" aquí Y ahora crearé 4 íconos más pero lo saltaré en este video porque puedes crearlos de la misma manera que lo hicimos para nuestro icono de mensaje aquí De acuerdo.
In the next couple of videos we are going to learn how to implement a navigation drawer into our app with which we can switch between different fragments We will build this navigation drawer from a scratch and I will split it up into 3 different parts because there are quite a few steps necessary In part one we will make some preparations We will add the necessary dependency create these icons and the menu file and make some changes to our activity theme In part 2 we will then create the navigation drawer itself and in part 3 we will handle click events on our icons here and open our fragments In the description box under each video you will find the link to the code for this example And I will release the remaining parts in the next couple of days Okay, let's start First we have to add the dependency for the design support library Because this contains the navigation drawer So we go into our build.gradle file with "(Module: app)" in its name And here at the bottom, we add this dependency For this we copy this copy this "appcompat" dependency completely with the "implementation" part Paste it one line below And we change the "appcompat-v7" to "design" Make sure to change the "v7" as well "design" We keep the version number the same as we have up here And when we have added this we click "Sync Now" Wait a short moment And when it's finished syncing we are ready to go Now Android Studio also offers a ready-made navigation drawer activity, which you can find when you right click on your package Go to "New" -> "Activity" and here you can find "Navigation Drawer Activity" When you click this you will get an activity completely with the navigation drawer and all the necessary code and it will look pretty similar to the one we are going to build But this navigation drawer won't open fragments And also if you don't know what each of the files does it can be very confusing so it's better to learn it by building it from scratch So we will skip this And implement this into our empty activity First we start with our icons So we open our "res" folder here open "drawable" and we right-click on "drawable" go to "New" and here we click on "Vector Asset" Then this window opens and here we click on this icon And then we can choose from a lot of different icons And you can choose whatever icons you want I'm gonna choose the same one as I had in the example The first one was this mail icon here Okay And I will slightly change the name to "ic_message" Because this is what the menu item in our navigation drawer will say Click "Next" And here on "Finish" And now we find our icon in this "drawable" folder here And I will now create 4 more icons but I will skip it in this video because you can just create them the same way as we did for our message icon here Okay.
Ahora tengo 5 íconos diferentes para nuestros 5 elementos de menú A continuación, tenemos que preparar un archivo de menú porque esto es lo que colocará nuestros elementos en nuestro cajón de navegación. Para esto, primero tenemos que crear una carpeta de "menú". Entonces, hacemos clic con el botón derecho en "res" Ir a "Nuevo" Y aquí creamos un nuevo "directorio de recursos de Android".
Un nuevo "Archivo de recursos de menú" Y le daré un nombre "drawer_menu" Hacemos clic en "Aceptar" Aquí abajo cambiamos a la pestaña "Texto" Y aquí pondremos todos los archivos de menú que queremos mostrar en nuestro cajón de navegación Los colocamos entre esas etiquetas de "menú" aquí Y primero creamos un grupo y agregamos el atributo "checkableBehavior" y lo configuramos como "único" Esto asegurará que solo podamos seleccionar un elemento de menú de los elementos que están dentro de este grupo Hacemos un ángulo de cierre corchete Y entre aquí ponemos diferentes elementos de menú Escribimos "<elemento" tenemos que darle una ID con android:id="@+id/" Y el primero será "nav_message" El siguiente atributo es "android:icon" Aquí escribimos "@drawable/" y luego el nombre del icono En mi ejemplo, este es "ic_message" Y un atributo más "android:title" que es el nombre de este elemento de menú que será "Mensaje" en este ejemplo Cuando hayamos agregado estos 3 atributos lo cerramos con la barra inclinada y un paréntesis angular de cierre Y luego copiamos este elemento Para los otros 2 elementos o cuántos desea agregar en su cajón de navegación Voy a cambiar el segundo a "nav_chat" Cambiar el ícono a "ic_chat" Y el título a "Chat" también Y el tercero será "nav_profile" "ic_profile" Y el título también será "Perfil" Y ahora de estos 3 elementos de menú solo podemos seleccionar 1 Y fuera de este grupo Vamos a poner 2 íconos más que son el ícono "enviar" y "compartir" en nuestro ejemplo, pero se comportarán de manera diferente.
No permanecerán seleccionados cuando los elegimos, sino que solo desencadenará una acción. Por lo tanto, no los colocaremos en este grupo con checkableBehavior="single", sino que debajo escribiremos "<item". otro menú Con "<menu" "</menu>" Y aquí pongo 2 elementos más "<item" Y al igual que hicimos anteriormente, agregamos un id android:id="@+id/nav_share" El ícono será "@drawable/ic_share" y el título también será "Compartir" Cierra esto Copia esto para el segundo elemento "nav_send" "ic_send" Y cambia el texto a "Send" Ahora podemos ver que estas 2 partes aquí son diferentes Tenemos este "<elemento> <menú> <elemento> <elemento>" y aquí tenemos <grupo> con 3 elementos Y esta parte inferior aquí creará una sección separada Esta sección tendrá una línea vertical Y luego el texto "Comunicar" De los 3 elementos en la parte superior podemos seleccionar 1 Se abrirá un fragmento y permanecerá seleccionado De los íconos en la parte inferior podemos hacer clic en ellos, desencadenarán una acción, pero no permanecerán seleccionados Puedes ver que en este ejemplo Estos elementos aquí permanecen seleccionados cuando los elegimos Pero esos aquí solo activan una acción Un mensaje de Toast en este caso, pero no permanecerán seleccionados Y aquí tenemos esta línea vertical y el texto "Comunicar" De acuerdo, de vuelta a nuestro proyecto Voy a presionar [Ctrl + Alt + L] para reorganizar esos atributos aquí y ahora se ve así Ahora, lo que también podemos hacer es subir aquí en la primera etiqueta de "menú".
Ir antes de este paréntesis angular de cierre y escribir "herramientas:" Si está en rojo, presionamos [Alt + Intro] Luego agrega este "xmlns: tools=…" atributo aquí Y luego podemos escribir "showIn" en mayúsculas y minúsculas con una 'I' mayúscula =" " y luego escribimos "navigation_view" Y como puede ver, cambia la vista a la que veremos en nuestro cajón de navegación Esto no es necesario, porque esto es solo para esta ventana de vista previa aquí Si no puede ver esta vista previa en su Android Studio, entonces puede subir aquí para "Construir", haga clic en "Reconstruir proyecto" Y luego tiene que esperar un momento y luego debería mostrar esta vista previa aquí correctamente De acuerdo , y ahora también tenemos que cambiar nuestro tema de actividad para deshacernos de la barra de acción predeterminada Porque nuestro cajón de navegación debería aparecer frente a la barra de acción Pero esto no es posible con la barra de acción predeterminada.
Now I have 5 different icons for our 5 menu items Next we have to prepare a menu file because this is what will get our items into our navigation drawer For this we first have to create a "menu" folder So we right-click on "res" Go to "New" And here we create a new "Android resource directory" From this drop-down menu here we choose "menu", which automatically changes the directory name We keep the rest as it is and click on "OK" Now we have this "menu" folder here We right-click on it And create a new "Menu resource file" And I'm gonna give it a name "drawer_menu" We click "OK" Down here we switch over to the "Text" tab And in here we will put all the menu files that we want to show in our navigation drawer We put them between those "menu" tags here And first we create a group and add the attribute "checkableBehavior" and set this to "single" This will make sure that we can only select one menu item from the items that are within this group We make a closing angle bracket And in between here we put different menu items We write "<item" we have to give it an ID with android:id="@+id/" And the first one will be "nav_message" The next attribute is "android:icon" Here we type in "@drawable/" and then the name of the icon In my example this is "ic_message" And one more attribute "android:title" which is the name of this menu item which will be "Message" in this example When we have added these 3 attributes we close it with the slash and a closing angle bracket And then we copy this item For the other 2 items or how many you want to add in your navigation drawer I'm gonna change the second one to "nav_chat" Change the icon to "ic_chat" And title to "Chat" as well And the third one will be "nav_profile" "ic_profile" And the title will be "Profile" as well And now from these 3 menu items we can only select 1 And outside of this group We gonna put 2 more icons Which are the "send" and the "share" icon in our example But they will behave differently They won't stay selected when we choose them but it will just trigger an action So we don't put them into this group with checkableBehavior="single" but instead below we write "<item" We give it an "android:title" just as we did for the menu items but this will create a section instead of a single item Gonna call it "Communicate" Close this And in here I put another menu With "<menu" "</menu>" And in here I put 2 more items "<item" And the same as we did above we add an id android:id="@+id/nav_share" The icon will be "@drawable/ic_share" and the title will be "Share" as well Close this Copy this for the second item "nav_send" "ic_send" And change the text to "Send" Now we can see, that these 2 parts here are different We have this "<item> <menu> <item> <item>" and here we have <group> with 3 items And this bottom part here will create a separate section This section will have a vertical line And then the text "Communicate" From the 3 items at the top we can select 1 It will open a fragment and it will stay selected From the icons from at the bottom we can click them, they will trigger an action, but they won't stay selected You can see that in this example These items here stay selected when we choose them But those ones here only trigger an action A Toast message in this case But they won't stay selected And here we have this vertical line and the "Communicate" text Okay, back into our project I'm gonna press [Ctrl + Alt + L] to rearrange those attributes here and now it looks like this Now what can we also do is we can go up here in the first "menu" tag Go before this closing angle bracket and write "tools:" If this is red, we press [Alt + Enter] Then it adds this "xmlns:tools=…" attribute here And then we can type in "showIn" in camel case with a capital 'I' =" " and then we type in "navigation_view" And as you can see it changes the view to the one we will see in our navigation drawer This is not necessary, because this is just for this preview window here If you can't see this preview in your Android Studio then you can go up here to "Build" click on "Rebuild Project" And then you have to wait a short moment and then it should show this preview here properly Okay, and now also have to change our activity theme to get rid of the default action bar Because our navigation drawer should appear in front of the action bar But this is not possible with the default action bar.
Entonces, tenemos que eliminarlo e implementar una barra de herramientas en su lugar. Una barra de herramientas es básicamente una versión más flexible de la barra de acción. Para esto, primero tenemos que deshacernos de la barra de acción predeterminada. Así que vamos a nuestra carpeta de "valores" aquí y abrimos "styles.xml". Y ahora tiene 2 opciones diferentes: puede eliminar la barra de acción para toda la aplicación.
Barra de una actividad en particular como lo haremos en este ejemplo, luego revertimos esto Y en su lugar, creamos un estilo separado Esto no es muy complicado Escribimos "<style" Tenemos que darle un nombre Y lo llamaremos "AppTheme.NoActionBar" Cierra esto con un corchete angular de cierre Y aquí agregamos 2 atributos: "<item" El primero es "windowActionBar" corchete angular de cierre Y aquí pasamos "false" Ahora un segundo elemento Nuevamente, "<item" "windowNoTitle" y establecemos esto a "verdadero" Esos son los mismos 2 atributos que se agregan en el tema "NoActionBar" Pero de esta manera podemos agregarlo en un nivel de actividad y aún así mantener nuestro AppTheme para toda la aplicación Agregaremos este tema que acabamos de crear a nuestra actividad en el archivo de manifiesto en un momento Luego eliminará la barra de acción pero esos atributos aquí aún se aplicarán a nuestra actividad porque está configurado como el tema de la aplicación Y todos los demás atributos que agreguemos a este "AppTheme" se seguirán aplicando a nuestro tema de actividad Solo sobrescribiremos estos 2 atributos Así que ahora vamos a nuestro archivo de manifiesto aquí "AndroidManifest.xml" Aquí buscamos nuestra ".MainActivity" Y antes de este corchete angular de cierre agregamos otro atributo "android:theme" y aquí buscamos "@style/AppTheme.NoActionBar" Y ahora esto eliminará la barra de acción solo para esta actividad en particular Las otras actividades mantendrán su barra de acción.
So we have to remove it and implement a ToolBar instead A ToolBar is basically a more flexible version of the action bar For this we have to first get rid of the default action bar So we go into our "values" folder here And open "styles.xml" And now you have 2 different options: you can either remove the action bar for the whole app For this you change the part up here to "Light.NoActionBar" This will remove the action bar for all activities And this is also the easiest way to do this If you just want to remove the action bar from one particular activity like we will do in this example, then we revert this And instead, create a separate style This is not very complicated We write "<style" We have to give it a name And we will call it "AppTheme.NoActionBar" Close this with a closing angle bracket And in here we add 2 attributes: "<item" The first one is "windowActionBar" closing angle bracket And in here we pass "false" Now a second item Again, "<item" "windowNoTitle" and we set this to "true" Those are the same 2 attributes that are added in the "NoActionBar" theme But this we way we can add it on an activity level and still keep our AppTheme for the whole app We will add this theme we just created to our activity in the manifest file in a moment Then it will get rid of the action bar but those attributes here will still be applied to our activity because this is set as the app theme And all other attributes we add to this "AppTheme" Will still be applied to our activity theme We will only overwrite these 2 attributes So now we go into our manifest file up here "AndroidManifest.xml" Here we search for our ".MainActivity" And before this closing angle bracket we add another attribute "android:theme" and here we search for "@style/AppTheme.NoActionBar" And now this will remove the action bar only for this particular activity The other activities will keep their action bar.
Porque están configurados para este
"AppTheme". Bueno, eso es todo para la parte 1. En el
siguiente video, crearemos el
cajón de navegación en sí mismo. Con el diseño y todo. Así que no olvides suscribirte al
canal para no perderte eso ..