从片段访问工具栏(及其子项)? [英] Access Toolbar (and its children) from fragment?

查看:71
本文介绍了从片段访问工具栏(及其子项)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building an application using the v7.widget.Toolbar component.

我能够将工具栏添加到我的活动中,但是我不知道如何(以及正确的方法?)从活动的片段中访问它.

I'm able to add the toolbar to my activity, but I don't know how (and what is the right way?) to access it from the activity's 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" />

这是我在活动中的使用方式:

Here's how I use it in the 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>

在我的活动的onCreate中:

In my activity's onCreate:

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

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

And now, for example, I want to access "@id/menu_1" from the Toolbar in my fragment, How do I do that?

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

getSupportActionBar() gives me the ActionBar, but I need the Toolbar

提前谢谢!

推荐答案

我不确定是否可行,但是您可以尝试一下.

I'm not sure if this works, but you can try it.

    final AppCompatActivity act = (AppCompatActivity) getActivity();
    if (act.getSupportActionBar() != null) {
        Toolbar toolbar = (Toolbar) act.getSupportActionBar().getCustomView();
    }

工具栏本质上是一个ViewGroup.

Toolbar is essentially a ViewGroup.

这篇关于从片段访问工具栏(及其子项)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆