1.布局文件
<androidx.appcompat.widget.Toolbar
android:id="@+id/title_tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
>
2.初始化 Toolbar
private void initToolbar(){
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
toolbar.setNavigationIcon(ContextCompat.getDrawable(this, R.drawable.toolbar_back));
toolbar.setOverflowIcon(ContextCompat.getDrawable(this, R.drawable.toolbar_more));
setTitle("标题demo");
}
3.更多按钮
(1) 更多按钮设置 (res/menu文件下)
<menu 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"
tools:context="com.example.toolbar.MainActivity">
<item android:title="Item" />
<item android:title="Item" />
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
</menu>
(2) 更多按钮的监听代码
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Toast.makeText(this,"进入设置功能",Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}