Home > Enterprise >  LayoutInflater how excatly make the new View
LayoutInflater how excatly make the new View

Time:01-13

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.

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

CodePudding user response:

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 setContentView 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).

CodePudding user response:

Ah sorry, for removing comment, i started texted and was pointless so I delted. Next time I will leave it, sorry my first time stockOverflow.

  • Related