ActionBar 选项卡由ScrollingTabContainerView 创建。 ActionBarView,即ActionBar 的实际View,包含一个方法ActionBarView.setEmbeddedTabView,它主要负责将选项卡放置在ActionBar 下方或嵌入到ActionBar 中。
当ActionBar 为initialized in Activity 时,它使用ActionBarPolicy 根据定义为true in the system's resources 但false in portrait mode 的boolean 值确定何时使用嵌入式选项卡。因此,在此初始化时,会调用 ActionBarImpl.setHasEmbeddedTabs 来确定选项卡的放置位置。而且,正如文档所述:
...当屏幕足够宽时,选项卡会出现在操作栏中
在操作按钮旁边
那么如何阻止它嵌入标签?
似乎你在这里有两个选择,一个显然比另一个更好,至少在我看来。
您可以使用反射来调用ActionBarImpl.setHasEmbeddedTabs 并将其设置为始终为false。您需要使用反射,因为ActionBarImpl 是一个内部类,并且没有公共的ActionBar 方法来指示何时嵌入选项卡。
您可以停止使用 ActionBar.Tab API 并切换到替代方案 like Google's SlidingTabLayout。这将要求您使用ViewPager,这通常是使用标签时的一个很好的优势,您甚至可能已经在使用它。
以下是两者的示例:
使用反射
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = getActionBar();
// Implement your tabs
...
try {
final Class<?> clazz = actionBar.getClass();
final Method embedTabs = clazz.getDeclaredMethod("setHasEmbeddedTabs", boolean.class);
embedTabs.invoke(actionBar, false);
} catch (final Exception ignored) {
// Nothing to do
}
}
反射结果
从固定标签切换到可滚动标签
要使用 Google 的 SlidingTabLayout,您需要将两个类复制到您的项目中。您需要的课程是:
实现SlidingTabLayout 的示例布局如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<your_path_to.SlidingTabLayout
android:id="@+id/slidingTabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
在扩展布局并使用View.findViewById 初始化SlidingTabLayout 后,调用SlidingTabLayout.setViewPager 将ViewPager 绑定到选项卡。
Check out Google's example for a full project
可滚动的标签结果
可滚动标签在 Google 的多个应用中使用,例如 Play Store 和 Play Music。如需演示它们的短视频,如果您不熟悉,请check out the Android design docs on tabs。
结论
简而言之,如果您不想嵌入它们,我会建议使用可滚动标签而不是固定标签(至少在横向模式下)。