Swipe-able screens in Android with ViewPager2 | Android Tutorial pt1

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up youtube in this video you are going to learn how to use vue pager 2 with adapters using your application to swipe through different screens and also using dot indicators which are super useful when it comes to tutorials to also show the user where he currently is throughout the tutorial but also in general if you want to have multiple screens that the user can swipe through so this will just be part one of the viewpager2 series in the next video you are going to learn even more about it there you are going to learn how to swipe through horizontally vertically using a tab layout and a lot more so definitely hit the subscribe button if you don't want to miss out and also hit the like button if you want to help us a little bit so let's get started [Music] [Music] hey and by the way we also have an article that you can find on our blog that is going over everything that you will see in this video with the code and also the resources so you can just download them from there definitely check them out and maybe you just want to read through it instead of just watching the video or just use it as additional material so check out the link in the description to get to the blog post all right so let's look at what we're going to build in this video and you can see that we are going to create swipeable screens in android with view pager too so you can either swipe here or you can just press this next key in order to swipe to the next selection and then once you're finished you will find this screen here where you will see that that you can swipe in the vertical direction or also swipe in the horizontal direction in order to jump to the next category so we have three categories we have the t shirts with double e and then we have the hoodies and then finally we have the sneakers here and depending on how we swipe we jump over to the other selections here so i'm already at the bottom which is why the swiping to the right doesn't work as well anymore but you can really see how this could be useful to your application and you can also click of course to these tabs and you can then swipe from there okay so let's build this but before we do that let's look at view pager too a little bit so let's look at examples of swipeable screens and cases where they are required in an application one of the applications of swipeable screens is feature introduction so it's popularly known as the onboarding screen where you show a user what they can find in the application another example is when you want to display different sections belonging to a category on the same screen we're going to build out these samples in this tutorial so viewpager2 is a better version of the traditional viewpager widget and it comes with more features like now you can easily enable vertical scrolling by adding it to the xml file as an attribute if you are already familiar with implementing a recyclerview then it comes even more easy for you to use viewpager2 with views just like a recyclerview as you can now extend recyclerview.com the fragment state adapter is a new adapter class that makes it easier to swipe between fragments because fragments are generally something you would use in mvvm for example and with the tab layout mediator you can easily attach a tab layout to a viewpager to show titles of each slide so i'd say let's go into the project and build this from scratch by the way on our website you can follow the instructions step by step and also get the code if you want to so just check out the link in the description to get that okay so let's start with an empty activity here and let's call this one fashion gallery i'm going to use api 21 and kotlin as usual now the first thing that we will need to do is to set up view binding because i'm going to use view binding in this project i'm going to use best practices here therefore we need to go all the way down here in our build.gradle app file and we need to add the build features here like so and the ones that i want to use is the view binding feature so i'm going to set that to true we need to add the dots indicator so i'm going to add an implementation here com tb1 normal colon dots indicator colon 4.2 at least that's going to be the version that i'm going to use so now let's sync that and then once that is synced we will need a bunch of drawables okay so you can use your own images i'm just going to use the ones that we have prepared here so all of those sneakers as well as hoodies and stuff okay so just drag in some images just make sure that you have the names ready here now inside of the values themes folder i want to make sure that i'm not going to use the action bar therefore i'm going to change that from dark action bar to no action bar i'm going to do that in all files or both files in the bright as well as the dark version all right now in my main activities xml so this one here activity underscore main xml i don't want to use this text view instead i'm going to use a view pager okay so view pager to widget and therefore i'm going to use the following settings so here i'm going to give this id of upager it's going to match parent in terms of width the height should be 400 density pixels and it should have a little bit of a margin and you can see where it's from it's from android x viewpager2.widget.viewedpager2 okay and then i will use dots indicators so it's these little dots that you can find here at the bottom they're pretty neat and that's what the that's what the dependency was for that we just added this tbo no more dots indicator okay so let's add those therefore i'm going to add this code here as you see so the constraints are important here of course it's to the start of parent to the end of parent we have a little bit of margin towards the top it is going to be the to the bottom of the view pager so basically this is underneath the view pager that we have right here and then then the layout width and height are wrap content we're going to use darker gray as the dots color the corner radius is basically how much you want the dots to be circle the dot size is the well the size of the dots i'm going to use 16 here spacing will be four density pixels so a little bit of distance and then the width factor will be 2.5 as well as this selected dot color will be purple 500 so this is just a color that is defined here which is this purple color okay so you can play around with these values i'm also going to set the progress mode so that we have this progress mode here where it shows you where you currently are at where it swipes or makes it thicker so you can just play around with those values to get different results then we need to make sure that we have this little button down there so i'm going to use a material button for this and so i'm just going to give it the text of finish so nothing too complex here just need to make sure that the constraints are set correctly set the margin towards top so that you have a little bit of a distance there so you see here this is the view pager then we have the dots and then we have the button i'm just going to say next next next and then we're going to override it at one point saying finish okay so that's the ui at least for the first screen and next we are going to require adapters so just like most widgets that display a lot of items view pager needs an adapter to easily control how each item is displayed on the screen there are two types of adapters that can be used with your pager two one of them is going to be recycleview.adapter just like a recyclerview you can use views with an item layout to build out your slides in view page or two if you know how to use a recycle view then this approach should be familiar to you and then there's the fragment state adapter this adapter is built to work well with fragments this way you can easily integrate view pages with fragments which we're going to see later so let's first of all start with the recycler adapter and therefore i'm going to need another layout here need to define how each individual item is going to look like so let's create a new file here inside of the layout folder of course and i'm going to call this one intro underscore items it should use constraint layouts everything else is fine and now let's check out the code here basically i want to have an image view at the top so i'm going to use app compat image view for that and you can see that my constraint layout is lacking some dependencies here so let me make sure that i have all name spaces added here correctly like so okay now the error disappears okay so now we need to have the app compact text view at least that's how i want to design this so every single item should have an image as well as a text view and then finally i want to have another text view so we have one that is for the title and the other one that is for the description so this the title wrapping the content having a little bit of margin 18 sp for its size being bold it's going to be to the end of the i can iv which is this one here our app compat image view and by the way if this is too fast you should definitely check out my android master class video where i teach you everything about xml and stuff so here we have this additional text view and basically this is how each individual item is going to look like image title description so this image is currently empty but we are going to populate it later on so you're learning something about android app development in this video and maybe you want to learn a lot more about it then you can check out one of my two courses so if you are a beginner android developer then i would highly recommend to check out my android master class course there you will learn to build android apps from scratch and you become a real android developer or maybe you want to become a better android developer because you are one already and you want to become a real pro then i would recommend to check out the jetpack master class because there you will learn how to use jetpack which is a suite of frameworks that will make sure that you are a senior app developer alright so i would really recommend to check out those courses if you want to step up your app development skills very quickly you can find a link in the description below which will send you to the course with a huge discount alright so thanks a lot for checking out those courses this really helps us out and this enables us to create these videos either way i wish you a nice journey to becoming a great app developer and now let's get back to the video okay so now let's go ahead and create a data class and i'm not going to make this too complex so let's just go ahead and create a new file here a data class let's call this one intro okay so this data class intro should have a photo which will be an integer so here then it needs to have a title which will be a string and then we have the description which will also be a string but the description isn't going to be nullable because we don't need to define it if we don't have an intro okay as it is with adapters we of course need to create an adapter class itself as well i'm going to call this one intro adapter like so and as adapters usually need data we're going to well a list of data we're going to call this one intro list which will be a list of intros okay so we need to pass a list of intros we're going to later on create an object file which has all of the data or fake data but of course you could replace this data with whatever source you have if you have that source from your aws server or if you have it from firebase or wherever the data comes from you can just send it to the adapter and the adapter will understand what to do with it now of course our intro adapter should inherit from a recyclerview class okay so we need to make sure that it inherits from the adapter class now it needs to know which view holder should use and i'm going to call this one intro adapter dot intro view holder so this is generally how i approach this there is no intro view holder at this given point but we're going to create one as an inner class in here okay so let's go ahead and create this inner class called intro view holder which will require a binding object because we're using view binding here and by the way if you want to learn more about view binding check out my video on how to use recyclerviews with viewbinding because we're not going to use findviewer by d neither are we going to use carton extensions we're going to use the best practices that google wants us to use and that is going to be view binding so here i'm going to use intro items and it was already given to me so let's select this intro items binding because we activated viewbinding right so this intro viewholder needs to inherit from recycleview.viewholder okay and i'm going to bind or pass the binding route to it that's generally the approach that you should take here okay so let's define this inner class what do we want to do there well basically we just want to bind items in there so let's create this function called bind item and pass the intro item to it so each individual item should be handled by this interview holder so what is it that we want to do well we're going to use this binding object that is given to us this one here from the root and we are going to use the description tv meaning text view we're going to get its text and we're going to populate it with the description then we need to get the title tv and we're going to populate its text property with the title from our intro and then finally we are going to use the icon and this was an iv so image view not a tv so not the text view and we're going to set the image resource here and the image resource should be the intro photo okay so basically what is going to happen here because there's a lot going on here basically we have this intro class right and it's going to be the format that our introduction it has okay so it has a couple of data so we're going to use this format where we get a photo we got a title and we got the description and what we want to do is we want to assign it to each individual introduction item so we want to add an image as well as a title as well as a description to it and as we want to use view pager and we want to be able to scroll through it so this is basically like a list that we have here that we want to scroll through so it's a like a recycler view right that's why we need to have an adapter again we're setting up this adapter we call it intro adapter and as it is with adapter so if you are not aware of what adapters are definitely check out my video on recyclerviews you will need to understand how recyclerviews work for this to even make sense i believe so we need to have an adapter and this adapter is using view binding in order to bind whatever we get from here the intro for the individual item that we're currently looking at for the description when we assign it to the intro items description then what we get as the title we assign it to the title and so forth this on our view holder and you see the interview holder is fine now now our intro adapter isn't looking very happy and that's because his members are missing so he's missing all of his buddies so let's implement those members and i'm going to implement all three of them you can use the shift key and then just mark all of them and then click ok and it will auto define those for you so what should happen once our view holder is created so once this oncreateviewholder method is called because it's an override function right it will be called by the system and not by us so once this adapter is coming into action this oncreateviewholder will be called for each item and here i want to return my intro view holder here it's this one here and now this inner class is actually being used so what else would i want to do there well i want to make sure that i pass to this interview holder object i passed the intro items binding and how that works is basically you need to inflate your view holder and you inflate it by passing the layout inflator to it so i'm going to use layout inflator.from and here you need to pass the context and i'm just going to say get the context from the parent because our adapter itself doesn't have a context it uses the context of the parent which means the main activity in which it's going to live okay so we're passing that and then you can add more parameters here for example you can say that the let me see what's the correct name here the view group will be the parent and the boolean which will be the additional flag that you need to pass which is attached to parent we're going to set that to false okay and that's going to be basically it so that's what the oncreateviewholder is going to do and this is complicated when you look at it the first time right but generally it's always structured like this so this is generally how you do it and you might think holy smokes what is happening here i don't get it well no worries you just need to structure it this way okay and the next time you're going to work with this the only things you would probably need to change let's say you have more details that you want to display would be which items you're going to bind so if you have not the description but instead you have i don't know an additional number or dates that you want to display or you have the amount of likes or whatever to display you would use this here and of course you would change the format of your data class accordingly okay now let's go back to the unbind view holder so how should every single view holder bind the data well the cool thing is we are using the holder which is our interview holder which is possible because we passed it here to our well we said that our adapter should use it and it's this class that we created here so basically we can now use this bind item function and that should do the trick so let's just say by the item and now there is something else that we get from the onbindviewholder we get the position so we know which item that we are currently looking at in our list so we have a list of three items in this particular example right we have this t-shirt we have the sneakers and then we have the hoodie right and this t-shirt has the id so the position here of zero this sneakers image or the sneakers entry has the id of one or the position of one and the hoodie has the position of two so basically we're just saying get me the intro list at the position that you are currently at so the entry of the intro list at the position that you're currently at okay so this intro list we're going to create it in a second i think it makes sense to create that next and then you will understand how everything is connected so here in the get item count we need to just return the amount of items we have in our intro list so in our case it's just three right but we want to make sure that this is going to be easily adjustable because we have dummy data and we have three entries but who knows our data that we get from the internet it could have an unlimited amount of data and unlimited i mean like thousands upon thousands of entries and that's the beauty here would take care of that for us so now let's actually create the data source and therefore i'm going to create an simple object because i don't want to use apis here will not work with an extra entries from a json class or whatever so instead let me create an object here all right so this object is going to be the page lists object so this object is going to just be containing a list of intervals so vial intro slides and it's going to be a list off and here i'm going to just enter the individual items so i'm just going to copy it in here because i believe it would otherwise be too boring to look at me go all right so here this will be my page list let me go over it real quick so here we have the t-shirts this will be the title we're going to use this image here you can see it here on the left hand side right this t-shirt you can jump on it by clicking the control key and clicking on it or holding ctrl key and clicking on it then we have the sneak you can do the same thing here this will be the sneakers and the hoodie so you can click on the hoodie and you will get that okay so you see that we have a little bit of a description this backslash n by the way is a line break so if you don't want this to be a super long text it will look weird on your phone you create a line break manually by using backslash n so the backslash here is an escape character and n is just saying new line so what this will do is it will create a new line for your description you can see that here customized backslash and hoodies in store so this is just something that we decided to do this way and you could of course leave that out it would look differently then okay so now let's connect the adapter to the view pager in our main activity because we set up the adapter we have the data source we say how the data should be structured so how each individual data item should be so what it should have in terms of properties but now in our main activity we don't know anything about that and especially we're using view binding and what we're doing here is no view binding so we need to make sure that we are in fact using view binding in our main activity and in order to do that we need to create a variable called binding well you can call it however you want i'm going to call this one binding and it will be using my activity main binding and i'm going to make this a nullable because i want to set it to null at the beginning okay and now the next part would be and by the way we're creating this outside because we want to be able to use it in different methods so we're creating it outside of any method so that's the idea of the scope that we're using here now let's create the viewpager so here pryvit var view pager this will be our viewpager2 object and it will be of type viewpager2 now let's make that this available as well because we're going to assign it later on okay so now that we have the viewbinding as well as the view pager let's go ahead and set up the binding inside of our oncreate and usually as you see we would set the content view based on their our layout activity main but as we are using view binding we can just assign the binding object here activity main and you would expect that you would use the activity main binding dot bind here but in fact you need to use the inflate because you need to inflate your layout basically and here you are going to use the layout inflator for that and now you can use the set content view so basically before that if you look at it so we had set this content view like this but now instead we are going to use the set content view with our binding so here we're going to say binding dot root and we need to add this question mark because well our binding object is of activity main binding optional there's this question mark here okay so we're going to say get me the root item what is the root item well you can hold the key control and then press on this root and you will see that this this constraint layout okay so basically what it says is it will inflate this xml file which just means in proper english terms it will display the constraint layout on your app's screen or on your phone screen so that's the idea all right so it's just fancy speak you know just a different way of doing it way more complicated but well google thinks it's greater this way so let's just do it and next we need to set up our view pager because we have prepared it here right but it's no so it's not going to do anything so what we will do here therefore is we're going to create a new function which i'm going to call setup view pager and i'm going to pass the activity main binding object binding here okay we're using view binding and that's generally how it's done with the setup view pager so we need to set up this view pager i'm just going to put it into an extra function here and i need to get the adapter and the adapter is going to be our intro adapter right the one that we set up for like 10 minutes or so even longer and we need to pass the list in here and i'm going to use the page lists intro slides okay so what the heck is this page lists intro slides well it's this object that we created and because we just created it as an object it's something that we can directly access so we didn't need to create an object of it inside of our main activity it just exists in this name same namespace here in com example fashion gallery it's in all this name namespace basically in the same folder right so now we can access its intro slides and this is just going to be this list the list of the different items that we have so here you could add more and more items manually i would definitely recommend you to check this out and yeah that would allow you to test this app a little more okay so now that we have the adapter we can go ahead and set up our viewpager so viewpager2 needs to have an adapter so we are just going to say view pager 2 binding dot view pager and this view pager needs the adapter as i said so let's go ahead and use viewpager2 which is now nullable adapter to be the adapter like so okay so first we need to initialize the viewpager and then we can use this view pager object in order to assign the adapter and where does the adapter come from well it is our intro adapter that we just created now we can go ahead and use this view pager nullable or optional or however you want to call it and here we need to register and let me use the correct term here so register on page change call back okay so we register an on-page change callback and we need to pass a callback that will work with it but we don't have one yet so let's quickly set one up and we're going to do that up here all right so it's going to be a global variable that we're going to set up here private eval paper or pager paper pager 2 call back which will be an object of you pager 2 dot on page change and i hope i wrote this correctly it doesn't seem like it so if it doesn't happen just go ahead and use object dot or colon actually not haha there we are so here view pager 2 dot on page change callback so what the heck is this on page change callback thingy so this on page change callback will be automatically called it's a callback right it's going to call back so to speak whenever this page is changing so on the change of the page meaning when this other page is coming into view then we need to do something so it's going to call back and then it's going to execute the code that we define here so here we can now say what we want to do so i will use a method called onpage selected and it's an override function so it means that this is going to be a function that is internally being called once the page is selected and the page that is at a certain position so what is this position well it's going to be the same position that we had in our on bind view holder so once again this one would be position 0 this would be position 1 position 2. okay so after it's calling it super function we're happy with that the constructor function we're good so now we can just check if the position is going to be equal to the page lists intro light here intro of course i need to write it correctly intro slides size -1 meaning once it's almost done let's change the text of our button so here we're going to use binding dot controller button dot text and we're going to set it to finish because if you look at the application we can press next next and once and once it is at its last point it changes to finish so once it is at the last position so to speak so that's how you get to find out what is the last position you just say okay give me the amount of items that saw the size inside of this list and then just use minus one because we're looking at the position and positions start collecting or counting at zero but lists basically have well if there are three entries a list has the length of three or the size of three but the position three would cause an error so that's why you need to make sure that you use one because the position three doesn't exist as there are only three entries and the entries are at zero one one and two okay so if you were to use three you would get a crash you could try it out you will love it so that's if we are the final position otherwise let's set this button to next so here next and also let's increase the number in the position so if you look at it once we click on this button it increases the position basically jumps to the next slide okay so if you want to achieve the same functionality you just go ahead and use binding dot controller button dot and here also this is a nullable again set on click listener and i'm going to use the one with curly brackets because then i can directly implement what should happen and what is it that i want to happen well i just want to use the view pager because it's available i need to add a question mark and i need to increment the current item so i'm just going to say use the current position plus one and that's it now we can use this pager to call back to pass to the register on page change callback because well it required a page callback a pager callback to be precise which is exactly what we now pass to it so that will be happy which is good if the code's happy we're happy now we can bind one more thing because this video is quite long already so i'm going to definitely split that into two parts otherwise it's my one and a half hour video so you can see we have these dots here right and they're pretty cool i love them but we haven't bound them yet we need to bind them slash we need to com connect them with the view pages position and therefore i'm going to use binding dots indicator with set view pager and here come on help me out here set view pager two okay and we're going to connect it with our view pager too but now we need to force unwrap it because another ball just doesn't work here so we're going to use the double exclamation mark because the view page is a nullable right but at this point we know that it's not going to be empty even though of course you could go ahead and use an if clause here and check if view pager is not empty and then do this but i'm just optimistic that it is going to work this way all right and now we can go ahead and make sure that our on destroy method is going to be implemented because you don't want to run into memory leaks in your application right so we need to overwrite the ondestroy method and unregister the callback to avoid that memory leak when no longer in use so you can just go ahead and set your viewpager2 with unregister on-page change callback with our pager to callback so the same thing that we here registered we need to unregister on destroy which will be called once our application is going to be shut down okay that's when the on destroy method will be automatically called we don't need to call that manually now if you were careful you would recognize that the setup view pager is grayed out so this method is never called and where would be a good point to call it well i would say in the oncreate method and now we just need to pass in the binding and the beauty is we have the binding available here so let's force it in here and therefore we need to add the exclamation marks because binding is nullable and it can't be null but we already initialized it just here so that should be fine so now a lot of stuff happened right we have already four classes and this is really just to get this page here to work but cool thing is now you can go ahead and use this as your basis and just replace individual aspects of it you can replace the structure that you have here adjust your ui for your intro items then well probably jump just make some minor changes to your bind item method and then you're good to go so of course your data source should be changed then as well but if you change those four things everything else should be pretty much the same and it will just work okay so i would recommend that you play around with it and test this then you will see that it actually works so before i uh speak big words let me actually try if it works even with my build because we're not even there at this cool part here right but let's just wait for it to load okay so i'm happy with it it worked let me show you so we have t-shirts let's click next we have sneakers let's click next and you see the button change to finish and also always this dots indicator is changing as well which is beautiful and we have the hoodie okay so now let me click finish and of course nothing happens and that's i would say something that we will implement in the next video so now just to show you real quick how easy it would be to change the structure that you have here so let's say we were to go and create another intro entry and therefore i need to add a comma here so here i have this new intro entry now let me check out which image i want to use in the drawables so of course it's not going to be a new style or new thingy let me use tea africa okay so here i'm going to use tea africa as the image i'm going to use the africa and this is just going to be another beautiful african t-shirt t-shirt well let's call it t-shirt like so okay let's test it again and now let's see how this is impacting our data that we see here so it already changed as you see so we have t-shirts we have sneakers we have hoodie and then we have our tea africa so beautiful african continent including madagascar here so that's brilliant and you can see we can swipe we can click this next button and it changes finish or to finish at the very last point okay so it doesn't change to finish at 3 but actually at the vast last point so our application is very easily adjustable now if you were to go and now change your intro items add another entry here at the bottom then go ahead and add it here add it into the adapter here at the bottom and that should be yeah that should be pretty much it and then make sure that you have it as the data itself and you're good golden so i hope you enjoyed this video and this is going to be useful to you but this is of course just part one so be prepared i'm going to upload part 2 very soon alright and that's it for this video i hope you enjoyed it if you did then please hit that like button and the subscribe button and also check out our android master class we are updating it to android 12 now so definitely check it out and also don't forget to subscribe to our newsletter you can find the link in the description below [Music]
Info
Channel: tutorialsEU - Android
Views: 267
Rating: undefined out of 5
Keywords: viewpager2 with fragments example in android, viewpager2 android kotlin example, viewpager2 android example, viewpager2 with tablayout android example, viewpager2 fragmentstateadapter example, viewpager2 with tablayout android kotlin example, viewpager2 with recyclerview adapter, android viewpager2, android tutorial, viewpager2 in android, viewpager2 android, android studio, android view pager, viewpager2, tutorial, kotlin, android development, android development tutorial
Id: Y946tVSRQmc
Channel Id: undefined
Length: 40min 33sec (2433 seconds)
Published: Mon Oct 18 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.