//ToolBarActivity
package com.animee.day04.demo02;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Toast;
import com.animee.day04.R;
public class ToolbarActivity extends AppCompatActivity {
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 关闭ActionBar
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_toolbar);
// 查找控件
toolbar = (Toolbar) findViewById(R.id.toolbar);
// 设置toolbar的信息
// 1.设置toolbar导航的图标
toolbar.setNavigationIcon(R.mipmap.menu);
// 2.设置显示的图标
toolbar.setLogo(R.mipmap.ic_launcher);
// 3.设置主标题
toolbar.setTitle("主标题");
// 设置二级标题
toolbar.setSubtitle("子标题");
// 设置菜单内容的方式
toolbar.inflateMenu(R.menu.toolbar_menu);
// 给toolbar当中的菜单添加点击事件
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
Toast.makeText(ToolbarActivity.this,"您点击了搜索按钮",Toast.LENGTH_SHORT).show();
break;
case R.id.notify:
Toast.makeText(ToolbarActivity.this,"您点击了提示按钮",Toast.LENGTH_SHORT).show();
break;
case R.id.collase1:
Toast.makeText(ToolbarActivity.this,"您点击了设置按钮",Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
}
}
//XML文件
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.animee.day04.demo02.ToolbarActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.Toolbar>
</LinearLayout>