Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to inflate or instantiate controls in Android?

I'm wondering if anyone can shed some insight as to the best practice for dynamically creating controls (inflate vs instantiate).

Inflate:

TextView styledText = (TextView)inflater.inflate(R.layout.styledTextView);

Instantiate:

TextView styledText = new TextView(mContext);
styledText.setTextAppearance(R.style.StyledTextStyle);

The object being created can either contain attributes in the inflated XML file, or be contained in a Style definition which is added to the instantiated object afterwards. (Assume that this styling includes width, background, text color, etc).

Haven't been able to run any time/memory tests of each method, was wondering if anyone knew which was quickest/most efficient.

like image 518
Adam Avatar asked Sep 17 '12 14:09

Adam


People also ask

Why We Use inflate in Android?

"Inflating" a view means taking the layout XML and parsing it to create the view and viewgroup objects from the elements and their attributes specified within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup.

What does it mean to inflate a layout in Android?

Layout inflation is the term used within the context of Android to indicate when an XML layout resource is parsed and converted into a hierarchy of View objects.

What is Inflater or inflate in Android?

LayoutInflater is a class used to instantiate layout XML file into its corresponding view objects which can be used in Java programs. In simple terms, there are two ways to create UI in android. One is a static way and another is dynamic or programmatically. Suppose we have a simple layout main.

What is inflation in Android Studio?

"Inflation" is a term that refers to parsing XML and turning it into UI-oriented data structures. You can inflate a view hierarchy, a menu structure, and other types of resources. Often this is done behind the scenes by the framework (when you call setContentView(R. layout. main) , for instance).


1 Answers

LayoutInflator has a slight overhead because it has to parse xml in order to build the object. It also temporarily takes more memory for the same reason. Other than that, it builds the View object in the same manner that you would anyway. It may be something to worry about if you call it hundreds of times a second for some reason. 99.9% of the time though you'll never know the difference.

Also to note, any method that accepts an xml resource like "setTextAppearance" will have the same xml parsing overhead. The only difference in the examples you provided is it's not parsing the TextView xml, but it would still have to parse the style attributes.

like image 72
DeeV Avatar answered Sep 22 '22 11:09

DeeV