工具栏位于页面顶部,引入工具栏的步骤如下:
(1)在styles.xml中定义一个不包含ActionBar的风格样式;
(2)给activity节点添加android:theme属性,并将属性值设为第一步定义的风格;
(3)将活动页面的XML文件根节点改成LinearLayout,且为vertical垂直方向,然后增加一个Toolbar节点
(4)打开活动页面的Java代码,在onCreate方法中获取布局文件中的Toolbar对象,并调用setSupportActionBar方法设置当前的Toolbar对象;
布局:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <androidx.appcompat.widget.Toolbar
- android:id="@+id/tl_head"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
-
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="0dp"
- android:layout_weight="1"
- android:orientation="vertical"
- android:padding="5dp">
-
- <TextView
- android:id="@+id/tv_desc"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textColor="@color/black"
- android:textSize="17sp"
- android:text="该页面演示工具栏功能" />
- </LinearLayout>
-
- </LinearLayout>
代码:
- package com.example.myapplication;
-
- import android.graphics.Color;
- import android.os.Bundle;
- import android.view.View;
- import androidx.appcompat.app.AppCompatActivity;
- import androidx.appcompat.widget.Toolbar;
-
- public class MainActivity extends AppCompatActivity
- {
- private final static String TAG = "ToolbarActivity";
-
- @Override
- protected void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- Toolbar tl_head = findViewById(R.id.tl_head); // 从布局文件中获取名叫tl_head的工具栏
-
- tl_head.setTitle("工具栏页面"); // 设置工具栏的标题文本
-
- // setSupportActionBar(tl_head); // 使用tl_head替换系统自带的ActionBar
-
- tl_head.setTitleTextColor(Color.RED); // 设置工具栏的标题文字颜色
-
- tl_head.setLogo(R.drawable.ic_app); // 设置工具栏的标志图片
-
- tl_head.setSubtitle("Toolbar"); // 设置工具栏的副标题文本
-
- tl_head.setSubtitleTextColor(Color.YELLOW); // 设置工具栏的副标题文字颜色
-
- tl_head.setBackgroundResource(R.color.blue_light); // 设置工具栏的背景
-
- tl_head.setNavigationIcon(R.drawable.ic_back); // 设置工具栏左边的导航图标
-
- // 给tl_head设置导航图标的点击监听器
- // setNavigationOnClickListener必须放到setSupportActionBar之后,不然不起作用
- tl_head.setNavigationOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- finish(); // 结束当前页面
- }
- });
- }
-
- }
PS:我这里直接用的,因为demo不支持5以下sdk。