【问题标题】:Android ActionBar Navigation Tabs looks differ in phones and tabletsAndroid ActionBar 导航选项卡在手机和平​​板电脑中的外观不同
【发布时间】:2013-11-20 10:30:28
【问题描述】:

ActionBar Navigation Tabs 是否可以在手机和平​​板电脑上显示相同?

请参阅下面的手机和平板电脑图片:

电话:

平板电脑:

Android documentation 声明“...当屏幕足够宽时,选项卡会出现在操作按钮旁边的操作栏中...”。 我们不希望它们出现在 ActionBar 中。有什么解决办法吗?

【问题讨论】:

标签: android android-actionbar


【解决方案1】:

ActionBar 选项卡由ScrollingTabContainerView 创建。 ActionBarView,即ActionBar 的实际View,包含一个方法ActionBarView.setEmbeddedTabView,它主要负责将选项卡放置在ActionBar 下方或嵌入到ActionBar 中。

ActionBarinitialized in Activity 时,它使用ActionBarPolicy 根据定义为true in the system's resourcesfalse in portrait modeboolean 值确定何时使用嵌入式选项卡。因此,在此初始化时,会调用 ActionBarImpl.setHasEmbeddedTabs 来确定选项卡的放置位置。而且,正如文档所述:

...当屏幕足够宽时,选项卡会出现在操作栏中 在操作按钮旁边

那么如何阻止它嵌入标签?

似乎你在这里有两个选择,一个显然比另一个更好,至少在我看来。

  1. 您可以使用反射来调用ActionBarImpl.setHasEmbeddedTabs 并将其设置为始终为false。您需要使用反射,因为ActionBarImpl 是一个内部类,并且没有公共的ActionBar 方法来指示何时嵌入选项卡。

  2. 您可以停止使用 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.setViewPagerViewPager 绑定到选项卡。

Check out Google's example for a full project

可滚动的标签结果

可滚动标签在 Google 的多个应用中使用,例如 Play Store 和 Play Music。如需演示它们的短视频,如果您不熟悉,请check out the Android design docs on tabs

结论

简而言之,如果您不想嵌入它们,我会建议使用可滚动标签而不是固定标签(至少在横向模式下)。

【讨论】:

  • 感谢您的出色回答。
猜你喜欢
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
  • 2014-07-27
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多