在xml
<android.support.constraint.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:toolBar=“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=".MainActivity">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toolbar"
/>
在主页面写逻辑
//获取toolbar对象
toolbar = findViewById(R.id.toolbar);
//一定要写在第一行
setSupportActionBar(toolbar);
//设置是否显示主标题、
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//设置标题
getSupportActionBar().setTitle("哈哈哈");
//设置主标题颜色
toolbar.setTitleTextColor(Color.RED);
//设置子标题及子标题颜色
toolbar.setSubtitle("subtitle");
toolbar.setSubtitleTextColor(Color.BLUE);
//设置是否显示左侧的按钮
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//给左侧的按钮
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MainActivity.this.finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@Override
public void onOptionsMenuClosed(Menu menu) {
super.onOptionsMenuClosed(menu);
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
return super.onMenuOpened(featureId, menu);
}
}