wtorek, 5 stycznia 2016

Android Tabs with Fragments, ViewPager and TabLayout optimized by AndroidAnnotations


This article was inspired by the situation. I wanted to use Tabs in my application. So I had generated the skeleton using IntelliJ IDEA. But this skeleton was full of deprecated stuff (for instance things like this: http://stackoverflow.com/a/28314294). I assume the same problem would happen with Android Studio. Since I was not satisfied, I decided to make the generated skeleton more actual according to API Level: 21 (Android 5.0 LOLLIPOP). But I also decided to introduce more clean way of implementation with using AndroidAnnotations. I share the final code.

Update Gradle dependencies

Configure your Gradle to use AndroidAnnotation as described here: https://github.com/excilys/androidannotations/wiki/Building-Project-Gradle

In addition add the following dependencies:

Create activity layout

First create the activity layout layout/activity_tabset.xml :

Create fragment 

Define layout for the fragment: layout/fragment_content.xml :

Define the logic:

Implement FragmentPagerAdapter

Now implement the adapter for your ViewPager.
Note that there are classes with underscore: TabsetActivity_.PlaceholderFragment_ which are generated by AndroidAnnotations. When everything is injected, this trick is not necessary. But here I could not use the Adapter as a bean and inject Fragment into it. The full explanation is in the last section. 

The Activity

Finally we can put all together in this simple activity TabsetActivity.java class.

Since Android Annotations are used here, please remember about some necessary thing regarding AndroidManifest.xml. You need to refer to the activity name with underscore, so it looks like following:


The result looks like below:


As you can see AndroidAnnotations made code more clean and simple to read.
You can compare with this classic way: https://github.com/codepath/android_guides/wiki/Google-Play-Style-Tabs-using-TabLayout .
There are lot of things in methods like onCreateView() or may lines of code to deal with argument parameters in fragment implementation. Also the activity became more clean.

I was considering what about injecting SectionsPagerAdapter. There is possiblity to inject adapters by making them @EBean. But not in this case. It has to be derived from the abstrac class FragmentPagerAdapter which has no parameterless constructor :(
You can see here: https://android.googlesource.com/platform/frameworks/support/+/refs/heads/master/v4/java/android/support/v4/app/FragmentPagerAdapter.java

In other case in the next step I would consider injecting also fragments using @FragmentById annotation.
So it looks like there is no possibility to rid off calls of the classes with underscore like: PlaceholderFragment_.builder() . In spite of this drawback, the possibility to use builder instead of classic way of implementation is still a value.

That's all.

I hope this is helpful.