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
MenuInflater
is class, You can find detailed Documentation HereMenuInflater
HereIt’s Kotlin’s syntactic sugar.
getXxx()
Java method can be invoked as if it was a Kotlinxxx
property.Reference: https://kotlinlang.org/docs/java-interop.html#getters-and-setters
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