Where is layoutInflater defined in this android app tutorial code?

Viewed 401

This Android tutorial introduces the concept of view binding, with this section demonstrating how to use it. In this case, the view binding is set up using the following code.

class MainActivity : AppCompatActivity() {

    lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }
}

The explanation for the call to ActivityMainBinding.inflate() is as follows:

This line initializes the binding object which you'll use to access Views in the activity_main.xml layout.

What this does not explain is where the variable layoutInflater is defined.

When using Android Studio, the code completion suggests that the variable "comes from getLayoutInflater()":

Snippet of Android Studio screenshot showing code completion for layoutInflater

getLayoutInflater() seems to be a method in Activity, but this doesn't help me understand what the reference to layoutInflater is doing, where it is defined, and how it is in scope at this point of the code. Can someone help me to understand this please?

1 Answers

ActivityMainBinding.java is the generated class by data binding which has a static method inflate(). When you pass the layoutInflater(it retrieve a standard LayoutInflater instance that is already hooked up to the current context) to inflate() it generates the same code under the code as we usually do while inflating the views and it fetches the layout name automatically.

So, the whole method is like

 public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater,
      @Nullable ViewGroup parent, boolean attachToParent) {
    View root = inflater.inflate(R.layout.activity_main, parent, false);
    if (attachToParent) {
      parent.addView(root);
    }
    return bind(root);
  }

I hope this is what you are looking and sure can help you. Thanks

Related