Android tricks – ViewPager and Offscreen Tabs

As I wrote in one of my first posts, we use Tabs a lot in our applications. They provide a grate way of navigating to different screens through our app. And in order to use tabs, we have to work with something call a ViewPager. According to the official documentation, this is a layout manager that allows us to flip left and right through pages of data. These pages of data are usually composed of Fragments. And in order to increase the performance and efficiency of the application, the views of each fragment / tab, which is offscreen, can be destroyed. The idea is to keep as little information in memory as possible. Sometimes this optimization can lead to problems, if the number of offscreen tabs is not set properly. User input can be lost, views’ state can be reset, etc. Thus, we need to carefully choose that number of offscreen tabs.

How can we do that?

By default, the number of offscreen tabs is set to 1. This means that there can be 1 tab to the left and 1 tab to the right of the currently visible tab, which will be kept in memory. Changing that value is fairly easy.

mViewPager.setOffScreenPageLimit(limit)

That’s all we need. The setOffScreenPageLimit() method will handle the rest.

Resources:

https://developer.android.com/reference/android/support/v4/view/ViewPager.html

Feel free to share, comment & give your opinion on the topic!

And only if you really REALLY liked the article, you can buy me a cup of coffee! Otherwise, don’t do it! Donate $1

5 thoughts on “Android tricks – ViewPager and Offscreen Tabs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s