[英]How to get the title or text from the toolbar for Android
I need some help with my java code for Android app.我需要一些关于 Android 应用程序的 java 代码的帮助。 I want to know how to find out what is the toolbar title when the title shows Inbox, Sent, Draft...etc?
我想知道当标题显示收件箱、已发送、草稿...等时如何找出工具栏标题是什么?
I have tried this:我试过这个:
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar_text = toolbar.getTitle().toString();
if (toolbar_text == "Inbox") {
//do something
}
It will not fetch the toolbar title as the toolbar_text will show null.它不会获取工具栏标题,因为 toolbar_text 将显示 null。 I want to know how I can fetch the text or title from the toolbar so I will then call the function to fetch the data from JSON.
我想知道如何从工具栏中获取文本或标题,因此我将调用 function 从 JSON 获取数据。
Here is the app_bar_main.xml:这是 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>
Here is what I want to get the "Inbox" text from the toolbar:这是我想从工具栏中获取“收件箱”文本的内容:
I have tried on google to find the answer but I couldn't find it anywhere.我已经尝试在谷歌上找到答案,但我无法在任何地方找到它。
Thank you in advance.先感谢您。
You can do this by getTitle()
if you are in an activity如果您在活动中,您可以通过
getTitle()
执行此操作
if (getTitle().equals("Inbox")) {
//do something
}
And prepend that with requireActivity()
if you are in a fragment如果您在片段中,请在前面加上
requireActivity()
if (requireActivity().getTitle().equals("Inbox")) {
//do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.