Is it possible for ActionBar Navigation Tabs to be displayed same on both phones and tablets?
See images for phone and tablets below:
PHONE:
TABLET:
The Android documentation states "...when the screen is wide enough the tabs appear in the action bar alongside the action buttons...". We don't want them to appear in ActionBar. Any solutions?
The
ActionBar
tabs are created by theScrollingTabContainerView
. TheActionBarView
, the actualView
for theActionBar
, contains a methodActionBarView.setEmbeddedTabView
which is essentially responsible for the placement of the tabs either below or embedded in theActionBar
.When the
ActionBar
is initialized inActivity
, it uses theActionBarPolicy
to determine when to use the embedded tabs based on aboolean
value that's defined astrue
in the system's resources, butfalse
in portrait mode. So, upon this initializationActionBarImpl.setHasEmbeddedTabs
is called to determine where to place the tabs. And also, as the docs state:So how do I stop it from embedding the tabs?
Seems like you have two choices here and one is clearly, at least to me, better than the other.
You can use reflection to invoke
ActionBarImpl.setHasEmbeddedTabs
and set it to always befalse
. You need to use reflection becauseActionBarImpl
is an internal class and there is no publicActionBar
method to indicate when to embed tabs.You can stop using the
ActionBar.Tab
API and switch to an alternative, like Google'sSlidingTabLayout
. This one will require you to use aViewPager
, which is usually is a nice plus when using tabs anyway and you may even already be using it.Here are examples for both:
Using reflection
Reflection results
Switching from the fixed tabs to scrollable tabs
To use Google's
SlidingTabLayout
, you'll need to copy over two classes into your project. The classes you need are:An example layout implementing the
SlidingTabLayout
would looks this like:After inflating the layout and initializing the
SlidingTabLayout
usingView.findViewById
, you callSlidingTabLayout.setViewPager
to bind theViewPager
to the tabs.Check out Google's example for a full project
Scrollable tab results
Scrollable tabs are used in several of Google's app, like the Play Store and Play Music. For a short video demonstrating them, if you're unfamiliar, check out the Android design docs on tabs.
Conclusion
In short, I would recommend using scrollable tabs rather than fixed tabs (at least in landscape mode), if you don't want them to be embedded.