因此,我有这个应用程序,并且在工具栏中有一个下拉菜单,我正在寻找一种解决方案,该解决方案仅显示特定片段上的特定项目。
我知道我必须制作一个Java类并将其链接到菜单,但是如何找出我所在的片段?
答案 0 :(得分:0)
您可以在启动这些片段的活动中移动为片段设置工具栏的实现。在这种情况下,您的活动中可能有工具栏,活动中应有一个片段容器,您将在其中放置片段。让我们为您的活动考虑以下布局。
<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();
希望您能明白。
请注意,这只是如何使动态工具栏在应用程序中工作的基本实现。但是,您的实现可能会根据您的用例而有所不同。
希望对您有帮助!
答案 1 :(得分:0)
我在工具栏中有一个ImageView,它隐藏如下:
// Show image in fragment 1
ImageView img = getActivity().findViewById(R.id.toolbarMenu);
img.setVisibility(View.VISIBLE);
// hide image in fragment 2
ImageView img = getActivity().findViewById(R.id.toolbarMenu);
img.setVisibility(View.GONE);
扩大布局后在onCreateView中尝试这些代码