Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

LayoutInflater how excatly make the new View

I’ve read one of answers here, and I am still confused.

""When I first started Android programming, I was really confused by LayoutInflater and findViewById. Sometimes we used one and sometimes the other.

LayoutInflater is used to create a new View (or Layout) object from one of your xml layouts.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

findViewById just gives you a reference to a view than has already been created. You might think that you haven’t created any views yet, but whenever you call setContentView in onCreate, the activity’s layout along with its subviews gets inflated (created) behind the scenes."

I think I understand so when LayoutInflater creat a new object View, why we can’t just do this:

view = new View(context);

view = findViewById(R.id.textView);

I missed something ? Thank you for anwsere.

I tried to undestrand way of working LayOutInflater

>Solution :

in simple words: LayoutInflater helps you to "exchange" layout written in XML to code, its kind of parser which take XML input and creates proper Views using Context (some simple way of new View object creation in first code line in your question)

Activity does that under the hood giving us devs simple setContextView and findViewById methods, but you may also want to add some custom View defined in XML additionally (because some if) or doring runtime, then you can use LayoutInflater based on same Context which views already created/shown are using (e.g. Activity itself)

note that when you use setContentView then LayoutInflater will attach some XML-based Views to Activity, so further line

view = findViewById(R.id.textView)

will return reference to already inflated existing View, meanwhile

view = new View(context)

is just creating some dummy View in memory using context, it isn’t added to Activity, Fragment, any shown ViewGroup, thus is not even visible (and its not same view instance than one found with findViewById)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading