titlebar

2025-05-23

android

志当存高远。—— 诸葛亮《诫外生书》

https://github.com/getActivity/TitleBar

Android 开发神器:TitleBar 的使用与优势解析

在 Android 开发中,标题栏(TitleBar)是应用界面设计中不可或缺的一部分。然而,原生的 ToolbarActionBar 功能有限且自定义成本较高,给开发者带来不少麻烦。为了解决这些痛点,TitleBar 组件应运而生。

今天我们来介绍一个开源库 TitleBar,它是由 getActivity 团队开发的轻量级标题栏工具,帮助开发者快速而灵活地实现标题栏功能。


为什么选择 TitleBar?

TitleBar 是一个功能强大且高度可定制的标题栏解决方案,以下是它的主要特点:

  1. 高度自定义:支持自定义标题、左右按钮、背景颜色等,满足各种 UI 需求。
  2. 轻量易用:只需简单配置即可快速集成,无需繁琐的代码。
  3. 兼容性强:支持 Android 各版本,且与多种布局兼容。
  4. 代码简洁:使用 TitleBar 可以大幅减少代码量,提升开发效率。
  5. 持续维护:由活跃的开源社区支持,拥有完善的文档和示例代码。

快速上手

以下是使用 TitleBar 的基本步骤:

1. 添加依赖

在项目的 build.gradle 文件中添加以下依赖:

1
2
3
dependencies {
implementation 'com.github.getActivity:TitleBar:latest_version'
}

确保将 latest_version 替换为 GitHub Releases 页面的最新版本号。


2. 在布局文件中使用

在 XML 布局中添加 TitleBar 组件:

1
2
3
4
5
6
7
8
<com.hjq.bar.TitleBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:title="主页"
app:titleTextColor="@color/white"
app:background="@color/blue"
app:leftIcon="@drawable/ic_back"
app:rightIcon="@drawable/ic_more" />

通过属性配置标题栏样式,例如:

  • app:title 设置标题文本。
  • app:leftIconapp:rightIcon 设置左右按钮的图标。
  • app:background 设置背景颜色。

3. 在代码中动态控制

TitleBar 提供了丰富的 API,可以在代码中动态控制其行为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
val titleBar = findViewById<TitleBar>(R.id.titleBar)

// 设置标题文字
titleBar.setTitle("设置页面")

// 设置左侧按钮点击事件
titleBar.setOnLeftClickListener {
finish()
}

// 设置右侧按钮点击事件
titleBar.setOnRightClickListener {
Toast.makeText(this, "更多选项", Toast.LENGTH_SHORT).show()
}

通过这些简单的接口,可以轻松实现标题栏的动态逻辑。


详细功能解析

1. 标题文字与样式

TitleBar 支持自定义标题文字、字体大小、颜色及对齐方式。

属性示例:

1
2
3
4
app:title="我的标题"
app:titleTextSize="16sp"
app:titleTextColor="@color/black"
app:titleGravity="center"

2. 左右按钮

支持添加左右按钮,并可设置图标、文本及点击事件。

属性示例:

1
2
3
app:leftIcon="@drawable/ic_back"
app:leftText="返回"
app:rightText="更多"

3. 背景与分割线

可设置标题栏背景颜色及底部分割线样式。

属性示例:

1
2
3
app:background="@color/white"
app:lineColor="@color/gray"
app:lineVisible="true"

实际应用场景

1. 简单主界面

在主界面中,使用 TitleBar 展示标题和返回按钮:

1
2
3
4
5
<com.hjq.bar.TitleBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:title="主页"
app:leftIcon="@drawable/ic_back" />

2. 自定义右侧功能菜单

在设置页面中,可为 TitleBar 添加右侧菜单按钮:

1
2
3
4
5
<com.hjq.bar.TitleBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:title="设置"
app:rightIcon="@drawable/ic_settings" />

通过接口实现点击事件:

1
2
3
titleBar.setOnRightClickListener {
openSettingsMenu()
}

总结

TitleBar 是 Android 开发中不可多得的标题栏解决方案,它不仅简化了标题栏的实现,还提供了强大的自定义能力。如果你正在寻找一个高效、灵活的标题栏工具,不妨试试 TitleBar

项目地址:https://github.com/getActivity/TitleBar