所以我有这个应用程序,并且在工具栏中,有一个下拉菜单,我正在寻找一种解决方案,该解决方案仅显示特定片段上的特定项目。
我知道我必须制作一个Java类并将其链接到菜单,但是如何找出我所在的片段?
您可以在启动这些片段的活动中移动为片段设置工具栏的实现。在这种情况下,您的活动中可能有工具栏,活动中应有一个片段容器,您将在其中放置片段。让我们为您的活动考虑以下布局。
<RelativeLayout>
<!-- Your toolbar here in the activity -->
<ToolBar>
android:id="+@id/toolbar"
...
</ToolBar>
<!-- Your fragment container here -->
<FrameLayout>
android:id="+@id/fragment_container"
...
android:layout_below="@id/toolbar"
</FrameLayout>
</RelativeLayout>
现在,您在活动中具有ToolBar
,因此,在将片段加载到片段容器中时可以设置工具栏。您的活动可能具有以下功能。
public void launchFrag1() {
// replace the fragment 1 in the fragment container
loadToolbarForFrag1();
}
public void launchFrag2() {
// replace the fragment 2 in the fragment container
loadToolbarForFrag2();
}
现在调用您活动的特定功能以动态加载片段和工具栏。
如果尝试从片段中调用方法,则始终可以像下面这样调用在活动中声明的方法。
((YourActivity) getActivity()).launchFrag2();
希望您能明白。
[请注意,这只是如何使动态工具栏在应用程序中工作的基本实现。但是,您的实现可能会根据您的用例而有所不同。
我希望有帮助!