Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java syntax explanation - getMenuInflater()

Just downloaded android studio, and I am using big nerd ranch's guide to android programming to learn the ropes.

When you start android studio this code is already in the main activity file:

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    **getMenuInflater().inflate(R.menu.menu_quiz, menu);**
    return true;
}

I don't understand the getMenuInflater line. In my short experience with java only an object comes before a method when using a period to separate the two such as in dog.bark(). Here it looks like the line means call the inflate method which is defined within the getMenuInflater method. However, I checked the source code for getMenuInflater(), and there is no inflate method in its body.

Can somebody demystify the syntax in this line for me?


2 Answers

The line getMenuInflater().inflate(R.menu.menu_quiz, menu); is a short form of this:

MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_quiz, menu)
like image 87
isma3l Avatar answered May 04 '26 01:05

isma3l


You are extending an activity and android studio adds that line for you to configure the menu for the layout, below is actual implementation of the method in the activity class :

 public MenuInflater getMenuInflater() {
            // Make sure that action views can get an appropriate theme.
            if (mMenuInflater == null) {
                initWindowDecorActionBar();
                if (mActionBar != null) {
                    mMenuInflater = new MenuInflater(mActionBar.getThemedContext(), this);
                } else {
                    mMenuInflater = new MenuInflater(this);
                }
            }
            return mMenuInflater;
        }
like image 45
rahulrv Avatar answered May 04 '26 00:05

rahulrv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!