如何从android工具栏中获取标题或文本

suzh9iv8  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(387)

我需要一些帮助我的java代码为android应用程序。我想知道如何找出什么是工具栏标题时,标题显示收件箱,发送,草稿…等?
我试过这个:

Toolbar toolbar = findViewById(R.id.toolbar);
toolbar_text = toolbar.getTitle().toString();

if (toolbar_text == "Inbox") {
   //do something
}

它不会获取工具栏标题,因为工具栏文本将显示为空。我想知道如何从工具栏获取文本或标题,然后调用函数从json获取数据。
以下是app\u bar\u 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>

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

我试过在谷歌上找到答案,但在任何地方都找不到。
先谢谢你。

z31licg0

z31licg01#

你可以通过 getTitle() 如果你在活动中

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

在这之前加上 requireActivity() 如果你是一个碎片

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

相关问题