EP22-ToolBar的前世今生

ToolBar的前世今生

上古时代

我们回想起Android 2.x时代的应用程序,那时候没有ActionBar/TitleBar的概念,但是会有一窄条;其实现在也有啦。。你可以打开铁路12306,在splash弹出来之前会看到上面一窄条灰色,那就是ActionBar的雏形了:

远古时代

后来出现了ActionBar,是在Activity顶部的。很不灵活。现在,如果你新建一个Activity什么都不做,默认就会有一个ActionBar。就不放图了。。AS创建的默认Activigty中,顶部蓝色的宽宽的那个就是。

近代..

API21之后,出现了ToolBar(可以用v7包支持API21以前的系统)。ToolBar是「ActionBar」的「精神继承者」。ToolBar的外观和行为比ActionBar要更容易定制。

使用ToolBar有两种方式:

  • 把ToolBar当成ActionBar来用,但想要获取更多对外观的控制。
  • 使用独立的ToolBar,ActionBar不支持的情况;比如显示多个toolbar(会有这种需求吗。。),只对部分的宽度做span等等。

注:下面的内容,大部分手动翻译自:https://guides.codepath.com/android/Using-the-App-ToolBar#advanced-scrolling-behavior-for-toolbar

ToolBar vs ActionBar

ToolBar和ActionBar的主要不同:

  • ToolBar像所有其他常规view一样,是一个包含在layout中的view(ActionBar不是这样哦)
  • 所以它可以很容易得被放置、加动画、和控制
  • 一个Activity中可以放置多个不同的ToolBar元素

记住,你仍然可以把ToolBar当成Activity的Action来设置。
另外,如果只需要一个顶部的静态的bar,可以放置icon,添加返回键,那么ActionBar仍然可用。

第一种情形:把ToolBar当成ActionBar来使用

  1. 首先在gradle里加上v7包。
  2. 禁用系统提供的ActionBar。最简单的方式是在res/styles.xml里面把你的主题继承的主题改成(不改的话,会出现一个ActionBar和一个ToolBar哦):
<resources>
  <!-- Base application theme. -->
  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">  <!--Theme.AppCompat.NoActionBar也行-->
  </style>
</resources>
  1. 现在你就可以在Activity的布局文件里面添加ToolBar了。一个使用ToolBar的便利的就是你可以在任何地方放置它。下面我们按照ActionBar一样把ToolBar放到最顶端:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
      android:id="@+id/toolbar"
      android:minHeight="?attr/actionBarSize"  
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:titleTextColor="@android:color/white"
      android:background="?attr/colorPrimary">
    </android.support.v7.widget.Toolbar>

    <!-- Layout for content is here. This can be a RelativeLayout  -->

</LinearLayout>

注意:
你可能需要给Toolbar的父类布局添加android:fitsSystemWindows="true""来保证activity的高度正确计算了。
另外,如果是在relativelayout里面,记得保证toolbar保持在顶部不要被覆盖。

  1. 在Activity或者Fragment中,使用setSupportActionBar(Toolbar)来把你的ToolBar当成ActionBar来用。
// Menu icons are inflated just as they were with actionbar
// Menu 图标跟在ActionBar中一样被渲染
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

然后呢,要记住在menu_main里面加入item哦。

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/miCompose"
        android:icon="@drawable/ic_compose"
        app:showAsAction="ifRoom"
        android:title="Compose">
    </item>
    <item
        android:id="@+id/miProfile"
        android:icon="@drawable/ic_profile"
        app:showAsAction="ifRoom|withText"
        android:title="Profile">
    </item>
</menu>

好了,这样就可以了。你可以添加点击事件。

重用(Reusing)ToolBar

许多应用里面,同一个ToolBar可以在很多Activity里重用的。怎么用?定义一个只包含ToolBar的资源文件(比如res/layout/toolbar_main.xml),然后用include就可以啦。

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"/>

然后再include。
这样的话你就有了在不同Activity中的「持续的navigation体验」。

更换Toolbar的Style

使用android:theme, app:titleTextAppearance, app:popupTheme可以更换TitleBar的样式。这里不细谈了。

展示App Icon

这样:

// Display icon in the toolbar
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);

如果想防止left margin把icon推得太远,可以加上contentInsetStart

<android.support.v7.widget.Toolbar
      android:id="@+id/toolbar"
      app:contentInsetLeft="0dp"
      app:contentInsetStart="0dp"
      ...
      >
</android.support.v7.widget.Toolbar>

自定义Title View

Toolbar终究只是一个装试过的ViewGroup,所以,其中的title是可以完全自己修改的。

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:minHeight="?attr/actionBarSize"  
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:titleTextColor="@android:color/white"
    android:background="?attr/colorPrimary">

     <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toolbar Title"
        android:textColor="@android:color/white"
        style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
        android:layout_gravity="center"
     />

</android.support.v7.widget.Toolbar>

这样的话,你可以在代码中通过:

TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);

来获取这个TextView。

Status Bar半透明(Translucent)化和透明(Transparent)化

类似前几个版本的QQ的那种。我个人认为不好看啦。用法是,在res/values/styles.xml里加上对main theme的一些额外设置。这里不介绍了。

对页面滚动的响应

比如,像知乎app那样实现向上滑动的时候toolbar消失效果:


借助 CoordinatorLayout,可以实现很多效果。
我们需要在 CoordinatorLayout里面,加上Toolbar和一个可滚动的container比如RecyclerView:

<!-- CoordinatorLayout is used to create scrolling and "floating" effects within a layout -->
CoordinatorLayout用来创建滚动和浮动特效。
<!-- This is typically the root layout which wraps the app bar and content -->
<android.support.design.widget.CoordinatorLayout
    android:id="@+id/main_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- AppBarLayout is a wrapper for a Toolbar in order to apply scrolling effects. -->
    AppBarLayout是一个wrapper,包裹着ToolBar,为了应用滚动特效。
    <!-- Note that AppBarLayout expects to be the first child nested within a CoordinatorLayout -->
    注意,AppBarLayout应该作为CoordinatorLayout的第一个child。
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

        <!-- Toolbar is the actual app bar with text and the action items --> 
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways" />
    </android.support.design.widget.AppBarLayout>

    <!-- This could also be included from another file using the include tag -->
    也可以使用include方式引入。
    <!-- i.e `res/layout/content_main.xml` -->
    <!-- `app:layout_behavior` is set to a pre-defined standard scrolling behavior -->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>  

关于ToolBar的滚动响应还有很多内容,这里不详细介绍了。


写的时候遇到的一些问题:

  1. 如果想在fragment里面应用TitleBar,要在onCreateView这样写:
//下面这两行缺一个都无法显示optionsMenu。
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
setHasOptionsMenu(true);

这样才会显示OptionsMenu。

  1. 使用mToolbar.setTitle(R.string.app_name);来设置tilte。

  2. 如果要控制OptionsMenu里面的项目显示不现实,在XML里写没有用了,要在Fragment里这样写:

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_main, menu);
        menu.getItem(0).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        menu.getItem(1).setShowAsAction(MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        menu.getItem(2).setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
        super.onCreateOptionsMenu(menu,inflater);
    }
  1. 如果想改变OptionsMenu的背景色,在Theme里添加:
<item name="android:itemBackground">@color/overflow_background</item>

Reference:
【1】https://guides.codepath.com/android/Using-the-App-ToolBar#advanced-scrolling-behavior-for-toolbar

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,976评论 25 708
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,489评论 2 45
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,498评论 0 17
  • 数据连接池的原理就是解决多次连接数据库的性能损耗,建立一个pool,用来存储数据库连接,需要的时候直接从连接池获取...
    孔垂云阅读 305评论 0 1
  • 文|娜 自己是个完美主义的人,一直以来尽力让自己的价值最大化,让自己无可替代,做任何事总不想麻烦别人、总想着无功不...
    稔诺紫na阅读 378评论 0 1