How to add an inflated view to a linear layout

mohan picture mohan · Sep 1, 2011 · Viewed 9.8k times · Source

How do you inflate a view and add it to a the list of child views of a LinearLayout?

Answer

Edward Brey picture Edward Brey · Oct 18, 2013

When you call the inflater constructor, set attachToRoot to false; then manually add the view after you've initialized it. Otherwise, you'll lose your initialization for all but the first child added.

Example:

View view = inflater.inflate(R.layout.some_view, parent, false);
((TextView) view.findViewById(R.id.some_text)).setText(someString);
parent.addView(view);

An example of what not to do:

View view = inflater.inflate(R.layout.some_view, parent);
((TextView) view.findViewById(R.id.some_text)).setText(someString);