java - 如何从 Android 的工具栏中获取标题或文本
问题描述
我需要一些有关我的 Android 应用程序 Java 代码的帮助。我想知道当标题显示收件箱、已发送、草稿...等时如何找出工具栏标题是什么?
我试过这个:
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar_text = toolbar.getTitle().toString();
if (toolbar_text == "Inbox") {
//do something
}
它不会获取工具栏标题,因为 toolbar_text 将显示为空。我想知道如何从工具栏中获取文本或标题,然后我将调用该函数从 JSON 中获取数据。
这是 app_bar_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/Theme.MyLogin.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/Theme.MyLogin.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="@layout/content_main" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:backgroundTint="#DA4336"
app:tint="@color/white"
app:srcCompat="@drawable/ic_edit_white_24dp" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
这是我想从工具栏中获取“收件箱”文本的内容:
我已经尝试在谷歌上找到答案,但我无法在任何地方找到它。
先感谢您。
解决方案
getTitle()
如果您正在参加活动,您可以这样做
if (getTitle().equals("Inbox")) {
//do something
}
requireActivity()
如果你在一个片段中,并在前面加上
if (requireActivity().getTitle().equals("Inbox")) {
//do something
}
推荐阅读
- html - DIV 重叠,低于该 div 的任何内容一直显示在 div 上
- sql - 使用多个 WHERE 有效地连接两个表
- html - 带有响应式图像的引导轮播
- google-sheets - Google 表格中带有 COUNTIF 的 ARRAYFORMULA
- discord - 如何在 DIScord.js 上批量删除频道?
- python - 为什么我在这个简单的 python 程序中得到结果 NONE?
- python - 在 Python 中重命名具有单引号的文件
- vue.js - 未从事件总线更新数据
- r - 计算列中的每个唯一值 - R
- python - Python中是否有任何语法来检查用户输入的整数是否包含特定数字?