如何在按下主页按钮时关闭溢出菜单 android?

How to dismiss overflow menu when home button is pressed android?

当我们点击三个点时,我正在显示溢出菜单列表。当我按下主页按钮并再次启动应用程序时,溢出菜单列表仍在显示。如何关闭溢出菜单列表 window?

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        Log.v("RAMKUMARV ONCREATEOPTION", "RAMKUMARV");

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);

        // Inflate the menu; this adds items to the action bar if it is present.
        //  getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem item = menu.findItem(R.id.action_settings);
        item.setVisible(true);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

MainActivity 级别声明菜单项,如下所示:

public class MainActivity extends AppCompatActivity {

    private MenuItem overflowItem;

    ...

}

现在您应该在 onCreateOptionsMenu 方法中实例化对象,如下所示:

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    ...

    overflowItem = menu.findItem(R.id.action_settings);
    overflowItem.setVisible(true);
    return true;
}

然后可以使用onPause方法设置overflowItem不再可见:

@Override
public void onPause() {
    super.onPause();
    overflowItem.setVisible(false);
}

最后记得用 overflowItem 替换你的 MenuItem item 对象。

要关闭溢出菜单,您只需在 Activity 中调用 closeOptionsMenu()

closeOptionsMenu()

Progammatically closes the options menu. If the options menu is already closed, this method does nothing.

您可以在 onPause() 方法中调用它,如下所示:

@Override
public void onPause() {
   super.onPause();
   closeOptionsMenu();
}

或者如果您只想在用户按下 Home 键时调用它,您可以使用 onUserLeaveHint(),如下所示:

@Override
protected void onUserLeaveHint() {
  super.onUserLeaveHint();
  closeOptionsMenu();
}

你可以有一个 activity 字段来存储 options/overflow 菜单,每当 onCreateOptionsMenu() 被触发时,然后使用 close() 方法在主页时关闭菜单单击按钮,即 onUserLeaveHint().

public class MainActivity extends AppCompatActivity {

    // Field to store the overflow menu
    private Menu mOverflowMenu;

    // omitted rest of your code

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        mOverflowMenu = menu;
        
        // omitted rest of your code
        return true;
    }
    
    // Dismissing the overflow menu on home button click
    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        mOverflowMenu.close();
    }   
    
}