Toolbar的简单使用

2017-04-01  本文已影响0人  MrAbel

隐藏ActionBar

任何一个新建的项目中都会包含一个默认的标题栏(ActionBar),这是因为在AndroidManifest.xml中的android:theme="@style/AppTheme"属性,为了在项目中使用Toolbar,必须先将ActionBar隐藏掉。而这个属性是在res/values/styles.xml中定义的:

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

可以将AppTheme的父主题修改为Theme.AppCompat.Light.NoActionBar(浅色)或Theme.AppCompat.NoActionBar(深色)来隐藏ActionBar

在布局中引入Toolbar

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        />
</LinearLayout>

这里要注意一下Toolbar的属性设置。

在代码中设置Toolbar

private Toolbar mToolBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   
    mToolBar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(mToolBar);
}

修改Toolbar的标题

默认情况下Toolbar的标题为应用程序名,可以通过修改相应Activity中的android:label属性来修改标题名

上一篇 下一篇

猜你喜欢

热点阅读