用片段内的新菜单替换BottomAppBar菜单

时间:2019-06-22 18:49:32

标签: android android-fragments menu

我正在将底部的应用栏和导航抽屉一起使用。当我单击抽屉中的一项时,将在我的主活动顶部添加一个新片段。在此片段中,我想要一个RecyclerView。贴上片段后,我想在MainActivity上看到我正在放大的普通菜单,但是当在“回收站”视图上单击某个项目时,我想用自定义菜单替换该菜单。现在,它只是将更多项目添加到现有菜单中。如何替换为新菜单并使Fab Button消失或向右移动?

enter image description here

该按钮仅用于模拟对我未来的RecyclerCiew的点击。

public class CourseFragment extends Fragment {
private Menu mMenu;
private MenuInflater mInflater;


public CourseFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.fragment_course, container, false);
    Button btn=view.findViewById(R.id.button);



    btn.setOnClickListener(v->{
        mInflater.inflate(R.menu.bottomappbar_edit_remove_menu,mMenu);mMenu.
    });
    return view;

}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    mMenu=menu;
    mInflater=inflater;
    //inflater.inflate(R.menu.bottomappbar_main_menu,menu);
    //super.onCreateOptionsMenu(menu,inflater);
}
}

1 个答案:

答案 0 :(得分:1)

在您的RecyclerView中,您需要实现一个OnClickListener来通知您 包含所需菜单的片段,然后调用 invalidateOptionsMenu() 再次运行 onCreateOptionsMenu()并构建新菜单。

使用带有按钮的示例,代码将如下所示

private int menuId = R.menu.bottomappbar_main_menu; // Your initial menu
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_course, container, false);
    Button btn = view.findViewById(R.id.button);

    btn.setOnClickListener(v -> {
        this.menuId = R.menu.bottomappbar_another_menu; // another menu that you want to use
        getActivity().invalidateOptionsMenu(); // notify that menu needs to be changed
    });
    return view;

}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // Inflate your menu
    inflater.inflate(this.menuId, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

别忘了您将需要使用所需选项创建一个新菜单文件