简体   繁体   English

OnBackPressed 用于 Fragment 并关闭菜单项

[英]OnBackPressed for Fragment and close menu items

I have a mainActivity with 3 fragments, in all fragment I have different menu items.我有一个带有 3 个片段的mainActivity ,在所有片段中我都有不同的菜单项。

If I open the searchview and press the back button, the program will close but I expect to close the searchview.如果我打开搜索视图并按下后退按钮,程序将关闭,但我希望关闭搜索视图。

How do I enable the back button function to close the menu item?如何启用后退按钮 function 以关闭菜单项?

When you are pressing back, onBackPressed() method of MainActivity is invoked.当您按下返回时,会调用MainActivityonBackPressed()方法。 Just override onBackPressed() in your activity and delete the super.onBackPressed();只需在您的活动中覆盖onBackPressed()并删除super.onBackPressed(); finally do your desire task.(you can set a flag to check if the searchview is open then after pressing the back button close it)最后做你想做的任务。(你可以设置一个标志来检查搜索视图是否打开,然后按下后退按钮关闭它)

@Override
public void onBackPressed() {
   //do your task here...
   //if search is open, close it
}

override your onBackPressed() in your activity.在您的活动中覆盖您的 onBackPressed() 。 check in there if there is an open fragment.如果有打开的片段,请检查那里。 if there is an open fragment you dismiss the fragment, else call super.onBackPressed()如果有一个打开的片段,则关闭该片段,否则调用 super.onBackPressed()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM