What does this method do super.onCreateOptionMenu() and super.onOptionsItemSelected(item)

后端 未结 4 1811
北恋
北恋 2021-01-24 09:40

I am new to android. I know this question have been asked before but, i am still confuse . What this method does when returning them inside my onCreateOptionMenu() and onOptionI

4条回答
  •  天涯浪人
    2021-01-24 10:06

    Ok, let's first see the two methods of your interest

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

    if return true ==>>> It means you want to see the option menu which you have inflated. if return false ==>>> you do not want to show it

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
        int id = item.getItemId();
    
        if (id == R.id.action_settings) {
            return true;
        }
        // Activate the navigation drawer toggle
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
    
        return super.onOptionsItemSelected(item);
    }
    

    As per documentation true --> Event Consumed now It should not be forwarded for other event false --> Forward for other to consume

    This Boolean return type actually benefits when we are working with multiple fragments and every fragment has their own Option menu and Overriding of OnOptionItemSelected(Mainly in tablet design)

    In this case android trace every fragments OnOptionItemSelected method so to avoid that

    a) If any fragment is consuming event in onOptionsItemSelected() so return "true" else return "false"

    b) If We return false then It will trace other connected fragment's (onOptionsItemSelected) method until it ends all fragment or Somebody consumes It.

    And your 3rd answer is as KrishnaJ written

    super.onCreateOptionMenu() and super.onOptionItemSelected

    If you write this then It will first call your parent class this method If you extend any class in this class.It will work as parent class if Methods are in parent class too.

提交回复
热议问题