您的位置:首页 > 其它

Material Design学习之Toolbar的使用(1)

2017-11-05 14:06 134 查看


Toolbar的使用:


准备活动:

任何一个新建项目默认的都是显示ActionBar,其实这是根据项目中指定的主题来显示的。打开AndroidManifest.xml文件,如下:

<application
   android:allowBackup="true"
   android:icon="@mipmap/ic_launcher"
   android:label="@string/app_name"
   android:supportsRtl="true"
   android:theme="@style/AppTheme" >
   ...
</application>


可以看到Android:theme指定了APPTheme的主题,而这个主题实在res/values/styles/.xml文件:

<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>
</style>

这里定义了APPTheme的主题,如过我们使用Toolbar来代替ActionBar,需要指定不带ActionBar的主题:

Theme.AppCompat.Light.NoActionBar(主题颜色设为深色,陪衬颜色为浅色);

Theme.AppCompat.Light.NoActionBar(淡色主题);


修改代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:id="@+id/activity_main"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <android.support.v7.widget.Toolbar
       android:layout_width="match_parent"
       android:layout_height="?attr/actionBarSize"
       android:id="@+id/toolbar"
       android:background="?attr/colorPrimary"
       android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
       app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
   </android.support.v7.widget.Toolbar>
</RelativeLayout>

解释:为什么用xmlns:app的命名空间:这是由于Material Design实在Android5.0系统中出现的,有很多Material属性之前不存在,为了兼容老系统使用app:attribute;android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar":我们将程序设为了浅色主题,为了和主题颜色区分开,ToolBar上的元素就会自动使用深色,为了让Toolbar单独使用深色主题,使用Android:theme。那么这样弹出的菜单也会为深色主题,使用app:popupTheme将弹出的菜单设为单色主题。MainActivity文件中加入:

     Toolbar toolbar;
       toolbar = (Toolbar) findViewById(R.id.toolbar);
       setSupportActionBar(toolbar);

这样运行效果和之前ActionBar看起来一样,接下来运用Toolbar的常用功能,添加action按钮添加按钮右击res目录-》new-Directory,创建Menu文件夹,右击menu文件夹,new
Menu resource file,创建Toolbar.xml文件,编写代码如下:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto">
   <item
   android:icon="@mipmap/ic_launcher"
   android:title="Backup"
   app:showAsAction="always"
   android:id="@+id/back_up"/>
   <item
       android:icon="@mipmap/ic_launcher"
       android:title="delete"
       app:showAsAction="always"
       android:id="@+id/delete"/>
   <item
       android:icon="@mipmap/ic_launcher"
       android:title="settings"
       app:showAsAction="always"
       android:id="@+id/Settings"/>
​
</menu>

app:showAsaction:指定按钮的显示位置,always(永远显示,屏幕不够则不显示)ifRoom(屏幕如果够则显示,不够再菜单里显示) never(永远显示在菜单中)Toolbar中的action按钮只显示图标,菜单中的action按钮只显示文字。修改MainActivity中的代码:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: