S
S
Saymon_K2014-07-01 13:59:18
Android
Saymon_K, 2014-07-01 13:59:18

Android: LayoutInflater - why is it needed?

Good afternoon!
I started to study Android and now I came to the topic about LayoutInflater. No matter how much I searched for explanations in Google Search and in the books of various writers, I still couldn’t understand: what is this thing? And why not use the shorter findViewById instead? After all, they both take an element (any View) from the xml file in order to work in the code.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey M, 2014-07-01
@Saymon_K

The LayoutInflater class contains a method:

public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
        if (DEBUG) System.out.println("INFLATING from resource: " + resource);
        XmlResourceParser parser = getContext().getResources().getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

Accordingly, the parser parses xml and converts it into an object of the View class;
When you specify setContentView(int id); in an Activity
You are passing a reference to xml. Inside the Activity is an instance of the Window class, it parses your xml and receives an object of the View class. Further, when calling in Activity - findViewById (int id), you refer to an instance of the Window class, in turn, it delegates (passes the call) to an instance of the View class.
And the View class contains the findViewById(int id) method, and it already returns the desired object, respectively, in both cases the mechanism is the same, only LayoutInflater is usually used to parse xml of non-layout Activities. For example, when rendering Fragments and CustomView or when linking an Activity from Java.
Look at the SDK sources, everything is described in great detail there.

B
bimeg, 2014-07-01
@bimeg

findViewById doesn't work with xml. It works with the View tree. But in order to make this tree from xml, LayoutInflater is just needed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question