Search code examples
androidlayout-inflater

Reuse inflated view for multiple tabs


I'm writing an app with multiple tabs. Every tab is a fragment and every tab uses the same layout file. You can change to the next tab by swiping (handled by a SwipeAdapter). Inflating the same layout for every tab again is quite inefficient and makes the app lag. Is there a way to inflate the layout once in the beginning and to reuse the inflated layout for all tabs?

Or alternatively, is there a way to do so with e.g. three inflated layouts? (-> one for each the currently displayed tab and both neighbours, so when you swipe from tab 4 to 5, the inflated layout of tab 3 - which is not needed anymore - is used for tab 6)

I know you can reuse inflated views with a listview, but it wouldn't work here because I want the user to swipe instead of continuous scrolling.


Solution

  • Welcome to StackOverflow. Use RecyclerView with a SnapHelper (works both horizontally and vertically). If you Google it you will find many tutorials.

    Alternatively you can use ViewPager2, which is in alpha state (if you can wait for it to be stable). It is based in RecyclerView, and is an update to the old ViewPager to bring it to 2019. See this tutorial for example Hands on With ViewPager2. See also ViewPager2 releases page at Google to keep track of development progress.