常见属性详解
android:layout_width="match_parent"
:设置标准工具栏的宽度android:layout_height="?attr/actionBarSize"
:设置高度android:background="#0090FF"
:设置背景颜色app:navigationIcon="@drawable/baseline_arrow_back_24"
:导航图标app:title="设置主标题"
app:titleTextColor="#ff0000"
:设置主标题字体的颜色app:subtitle="子标题"
app:subtitleTextColor="#00ff00"
:设置子标题字体的颜色app:logo="@mipmap/ic_launcher"
:设置logo
项目结构
主要代码
java
package com.study.mytoolbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolBar = findViewById(R.id.tb);
toolBar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("toolbar", "onClick: toolBar被点击了");
}
});
Toolbar toolbar2 = findViewById(R.id.tb2);
toolbar2.setNavigationIcon(R.drawable.baseline_arrow_back_24);
toolbar2.setTitle("标题");
toolbar2.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("toolbar2", "onClick: toolBar2被点击了");
}
});
}
}
activity_main.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/tb"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#0090FF"
app:logo="@mipmap/ic_launcher"
app:navigationIcon="@drawable/baseline_arrow_back_24"
app:subtitle="测试子标题"
app:subtitleTextColor="#00ff00"
app:title="测试标题"
app:titleMarginStart="90dp"
app:titleTextColor="#ff0000" />
<androidx.appcompat.widget.Toolbar
android:id="@+id/tb2"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_marginTop="20dp"
android:background="#ffff00" />
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_marginTop="20dp"
android:background="#ff00ff"
app:navigationIcon="@drawable/baseline_arrow_back_24">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="标题" />
</androidx.appcompat.widget.Toolbar>
</LinearLayout>