目录
3 FloatingActionButton 悬浮按钮和可交互提示
1.Toolbar
还记得我们每次打开的程序的标题栏吗?那不是 toolbar 做的 , 那是 actionbar 做的 , Toolbar 可以说是 Actionbar 的升级版了。 Toolbar 不仅有 Actionbar 的所有功能 , 而且还更加灵活 .
在项目运行在虚拟机上时,都可以看见屏幕上方有一个栏目(下图红框圈出的部分),此为系统默认的
DarkActionBar
,可在
themes.xml
中查看。

去掉系统默认栏目的的方法:
以便于我们更灵活的编辑栏目内容,所以我们先将主题文件中的
DarkActionBar
改为
NoActionBar
,再次运行就可以发现顶端的栏目不见了
1.1基本框架
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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"
android:orientation="vertical"
android:id="@+id/drawer"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/teal_200"
app:navigationIcon="@drawable/ic_baseline_arrow_back_ios_24"
app:title="Xisq's APP"
app:titleTextColor="#2A91E3"
app:subtitle="Android学习笔记"
app:logo="@mipmap/logo"
app:titleMarginStart="60dp"
app:menu="@menu/toolbar_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
注意尖括号里不是普通的
Toolbar
,而是
androidx.appcompat.widget.Toolbar
。
1.2常用属性
属性
|
说明
|
app:navigationIcon
|
导航图标,一般情况下放回退按钮,点击退回上一个界面。
|
android:background
|
工具栏颜色
|
app:title
|
标题
|
app:titleTextColor
|
标题文字颜色
|
app:titleMarginStart
|
标题与左侧间距
|
app:subtitle
|
子标题
|
app:subtitleTextColor
|
子标题颜色
|
app:logo
|
工具栏
logo
|
1.3添加工具栏点击事件
给
Toolbar
加上
id
,我们就可以在
java
代码里获取并监听用户对工具栏图标的点击:
package com.hp.demo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.andr