What is onCreateOptionsMenu(Menu menu)

前端 未结 4 1036
太阳男子
太阳男子 2020-12-29 08:23

What are the two parameters Menu and menu in method onCreateOptionsMenu(Menu menu) and how to use this method. I have another question why this pa

4条回答
  •  心在旅途
    2020-12-29 09:01

    The intent of implementing this method is to populate de menu passed with the itens you define in the R.menu.game_menu layout file.

    Java

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.game_menu, menu);
        return true;
    }
    

    Kotlin

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.game_menu, menu)
        return true
    }
    

    After inflating the menu with the itens you might want to add some action when they are selected:

    Java

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_item:
                // Action goes here
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    

    Kotlin

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.menu_item -> {
                // Action goes here
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    

提交回复
热议问题