skip to Main Content

I’ve been studying Kotlin and Android development, and studying the code samples in Android Studio, I’ve encountered this block:

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

I know that first you have to instantiate a variable for the inflater to use the inflate() method, but there is no menuInflater variable in this code. Looking at it, I see that it is similar to getMenuInflater() but I don’t get how this is possible. I looked at the documentation and I have not found any explanation. Is menuInflater a variable, class, method?

Thank you in advance for the answer.

3

Answers


  1. MenuInflater is class, You can find detailed Documentation Here

    • Also you can find a simple example for MenuInflater Here
    Login or Signup to reply.
  2. It’s Kotlin’s syntactic sugar. getXxx() Java method can be invoked as if it was a Kotlin xxx property.

    Reference: https://kotlinlang.org/docs/java-interop.html#getters-and-setters

    Login or Signup to reply.
  3. menuInflater is an object you can take from activity since activity and Menu class which you take menuInflater
    shares common classes in the inheritance hierarchy. You can get the menuInflater object in activity, and it gives you chance
    to get a menu file to your activity and use it there, Inflaters are mostly used to get some layouts and use it in another
    layout e.g LayoutInflater, MenuInflater

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search