Tuesday, 21 May 2019

Kotlin for Android development essentials: ViewPager and Fragment

One of the common features in Android applications is swiping to change texts, images, buttons or complex combinations of those. In today's tutorial, I will show you how to do that in Kotlin programming language and Android studio 3.4.1.

Firstly, create a blank Android project (remember to choose Kotlin as the language) with an empty main activity; there will be two files created, MainActivity.kt for the activity and activity_main.xml for the layout of the activity.

To be able to swipe to change fragment (you can put texts, images, buttons, etc into a fragment), we need add view android.support.v4.view.ViewPager as a place holder of the fragment. We then can pass the fragment that we want to render to the ViewPager adapter which is linked to the ViewPager view.

Let's start by creating the layout for the main activity with ViewPager view on top of a simple text view. The layout code for the main activity is shown below.

The next step is to create the image fragment that shows the name of an image. There will be two files created, ImagesFragment.kt for the fragment and fragment_images.xml for the layout of the fragment. The image fragment class can be used to return a new image fragment instance with a new image name as the input parameter; this input parameter is then used to change the content of the only text view inside the image fragment. It is important to know that a fragment needs to be inflated to a view in onCreateView function before its children views (e.g., a text view in our case) can be accessed in onViewCreated function. Let's have a look at the image fragment class and layout.

The next step is to create the ViewPager adapter to control which fragment will be rendered in the ViewPager view. It is important to know that there are two types of adapters for different situations, FragmentPagerAdapter (fragments are stored in memory until the activity shuts down) and FragmentStatePagerAdapter (fragments that user does not see are destroyed). The source code for the adapter is shown below.

The final step is to go back to the main activity and create the link between the ViewPager view and the ViewPager adapter. The source code for this step is shown below.

Our app is ready to run now!!!

No comments:

Post a comment