3秒钟不懂你砍我:Toolbar,没有废话的纯教程

1.隐藏Toolbar

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
2.xml(它是容器控件)

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#FFE4E1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="Title"/>

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

3.修改状态栏颜色

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">#FFE4E1</item>
    <item name="colorPrimaryDark">#FFC1C1</item>
</style>

4.设置属性(1.被注掉的是activity中设置Toolbar的方式2.设置navigationIcon要在设置Toolbar后,用于设置菜单)

java

toolbar.setTitle("Title");
        toolbar.setSubtitle("SubTitle");
        toolbar.setLogo(R.mipmap.ic_launcher);

//        setSupportActionBar(toolbar);
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.ic_launcher_round);

xml

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="50dp"
    toolbar:logo="@mipmap/ic_launcher"
    toolbar:subtitle="SubTitle"
    toolbar:title="Title"
    toolbar:titleTextColor="#FFE4E1"/>


5.弹出菜单

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}
(res/menu/menu.xml)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_settings"
        android:title="设置"
        android:orderInCategory="100"
        android:icon="@mipmap/ic_launcher_round"
        app:showAsAction="never"/>
</menu>


6.修改弹出位置

<style name="popup_theme" parent="@style/ThemeOverlay.AppCompat.Light">
    <!--设置不覆盖锚点-->
    <item name="overlapAnchor">false</item>
</style>
(toolbar中新增)

app:popupTheme ="@style/popup_theme"
7.点击事件

mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        Toast.makeText(MainActivity.this, "pizza", Toast.LENGTH_SHORT).show();
        return true;
    }
});