自从参加了某比赛之后,对Android开发似乎失去了兴趣,东学学西学学但都停留在一些很表面的东西上面。思考了很久,到底对什么东西感兴趣之后,最终还是回到了android上,废话不多说,开始toolbar的学习。 开始的时候遇到了很多的坑,大概用了一天?才勉强解决了问题
在Android3.0的时候谷歌推出了Actionbar的设计,如今在material design的推动下定义了一个新的名称 app bar 由Toolbar实现 因此!我们首先要在style中取消app的Actionbar
首先在res/values/style.xml中修改 <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="windowActionBar">false</item> <item name="android:windowNoTitle">true</item> </style> </resources> 为toolbar创建一个toobar.xml文件方便后续多个布局的引入,这里要使用v7.widget.Toolbar兼容较低版本的系统 <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="@color/maincolor" android:elevation="4dp"> </android.support.v7.widget.Toolbar>然后在layout_main.xml中引入toolbar
注意!注意!include标签必须放在LinearLayout或者RelativeLayout中,我之前配合DrawerLayout使用直接导致toobar全屏显示,如图
正确的代码如下:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <include android:id="@+id/toolbar" layout="@layout/toolbar" /> </LinearLayout> <include layout="@layout/drawer_layout"/> </android.support.v4.widget.DrawerLayout>