首页 > 解决方案 > 如何从 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>

这是我想从工具栏中获取“收件箱”文本的内容:

在此处输入图像描述

我已经尝试在谷歌上找到答案,但我无法在任何地方找到它。

先感谢您。

标签: javaandroidxmlandroid-toolbar

解决方案


getTitle()如果您正在参加活动,您可以这样做

if (getTitle().equals("Inbox")) {
   //do something        
}

requireActivity()如果你在一个片段中,并在前面加上

if (requireActivity().getTitle().equals("Inbox")) {
   //do something        
}

推荐阅读