android - 从 fragment 访问工具栏(及其子项)?

标签 android android-toolbar

我正在使用 v7.widget.Toolbar 组件构建应用程序。

我可以将工具栏添加到我的 Activity 中,但我不知道如何(以及正确的方法是什么?)从 Activity 的 fragment 中访问它。

这是工具栏

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
app:theme="@style/MainActionBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
tools:context=".MainActivity">

<ImageView
    android:background="@drawable/icon_1"
    android:paddingLeft="1dp"
    android:paddingRight="1dp"
    android:layout_marginLeft="19dp"
    android:id="@+id/menu_1"
    android:layout_gravity="center_vertical|left"
    android:src="@drawable/menu_burger"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<ImageView
    android:layout_marginRight="19dp"
    android:paddingLeft="1dp"
    android:paddingRight="1dp"
    android:id="@+id/menu_2"
    android:layout_gravity="center_vertical|right"
    android:src="@drawable/icon_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

这是我在 Activity 中使用它的方式:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/view_home_toolbar" />

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
     ...
     ...

</LinearLayout>

在我的 Activity 的 onCreate 中:

   Toolbar actionBar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(actionBar);

现在,例如,我想从 fragment 中的工具栏访问“@id/menu_1”,我该怎么做?

getSupportActionBar() 给我 ActionBar,但我需要工具栏

提前致谢!

最佳答案

无需编写大量代码:按照此操作

在 Kotlin 中:

   var toolbar = activity.findViewById<Toolbar>(R.id.toolbar)
    toolbar.setTitle("Rashid")

在 Java 中:

 Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
 toolbar.setTitle("Rashid")

关于android - 从 fragment 访问工具栏(及其子项)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28327745/

相关文章:

android - 分页文本并调整其大小

Android Toolbar 设置标题解释

android - 工具栏未隐藏在 RecyclerView 滚动条上

android - actionButtonStyle 不适用于支持库 v23.1.0

android - MPAndroidChart PieChart 如何更改中心文本以显示不同的颜色和字体大小

java - 保护 Android 中的信息

android - 如何在 recyclerview 中添加从左向右滑动

android - 使用 addView() 时我的应用程序崩溃

android - 带有 AppCompat-v7 的工具栏和上下文操作栏

android - Android 上的 OnOptionsItemSelected 在 Activity 中不起作用