ian lake: welcome to androiddevelopment patterns, where we help you build better apps. i'm ian lake. let's get to work. let's think about how younavigate through an app.
Android zoom imageview, you navigate to a detailedview from the parent view, or you can navigatebetween sibling views. that's where tabs andviewpagers come in. so what is a viewpager?
that's what controls the actualswiping between different pages of content. viewpager gets its contentfrom a pageradapter. this could be ageneric view-- one for each page-- orwhole fragments, if you use afragmentpageradapter or fragmentstatepageradapter. fragmentpageradapterkeeps each fragment it creates in memory, makingit lightning fast to switch
between already loaded tabs. however, this can getexpensive, memory-wise, if you have a largenumber of fragments. somethingfragmentstatepageradapter solves by destroying andrecreating fragments as needed, only saving the state. there isn't a lotto a pageradapter. you'll need to overridegetcount to return the number of pages you have.
then, in the case of afragmentpageradapter, you'll need toimplement getitem, which returns the fragmentassociated with each position. here, we'll just do asimple switch statement, selecting the rightfragment for each position. but you have the flexibilityto use any approach you want. the other thing wemight want to override is getpagetitle, returning astring describing each page. why would you want a page title?
well, those page titleswill be really helpful if you want to have some tabsassociated with your viewpager. tabs give users agreat way to see exactly what those pagescontain without having to scroll through each one. they also allow usersto jump between pages by tapping on a tab. the tablayout class, part of theandroid design support library, makes it easy to implement tabs,with all the material design
styling. and it's backwardcompatible to android 2.1. let's hook everything together. first, we need tohook our viewpager up to a pageradapterusing setadapter. then, hooking up a tablayoutis just a single method setupwithviewpager. with just that, you get tabsfrom the pageradapter's titles. and swiping through pageswill change the tabs,
and tapping on tabs will changethe pages-- as you'd expect. get started with thetablayout and viewpagers by adding the design library. be sure to check outthe design guidelines
and the detailed training docs. thanks for joining me here onandroid development patterns. use tabs and viewpagersto build better apps. [music playing]