Tuesday, July 31, 2012

Android ActionBar Tabs and ViewPager and RoboGuice in one app.

In a new Android app, I use the ActionBar and ActionBar Tabs, because they look good and integrate nicely with the rest of the Android UI. I also usually use a ViewPager in a number of activities, for displaying multiple fragments. Now, it turns out that the ActionBar Tabs and the ViewPager aren't compatible. The ViewPager only exists in the support package, so it only supports support package fragments out of the box. But the TabListener in the ActionBar only works with android.app.Fragment. You can work around this by having your own copy of PagerAdapter, from the Android source code, and make it use android.app.Fragment instead of the support Fragment. TechRepublic gives you some clues on how to do that.

My PagerAdapter extended android.support.v4.app.FragmentPagerAdapter, but this gave me an error because the super constructor expects a support fragmentmanager as a parameter, while I have an android.app.FragmentManager. I solved this by creating my own copy of FragmentPagerAdapter, which uses the right FragmentManager. Basically, I added
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
to my FragmentPagerAdapter.

However, I always use RoboGuice, and this posed an additional problem. RoboGuice uses the support.v4.Fragments, and now I needed the android.app.Fragments. I use an adapted RoboGuice source project anyway, so it was easy to replace the v4 fragments by android.app fragments in the RoboGuice source. This made my app, containing ActionBar Tabs in one Activity, and a ViewPager with android.app.Fragments in another Activity, work perfectly well.

No comments: