Android: Call to getLayoutInflater() outside activity

Some times we need the inflater outside activities in android . To get access to the inflator we may use the following code snippet. You can use this outside activities – all you need is to provide a Context:

LayoutInflater inflater = LayoutInflater.from(context);

the from function also checks with assert that you actually get an inflater back and throws an error otherwise – which will be much easier to deal with then a null pointer exception somewhere in the code.

An Alternate way is shown below but I recommend to use the above one:

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

Then to retrieve your different widgets, you inflate a layout:

View view = inflater.inflate( R.layout.myNewInflatedLayout, null );
Button myButton = (Button) view.findViewById( );
RECOMMENDED READ  Android Libraries and tools collection

Dost Muhammad Shah

Dost Muhammad specializing in Embedded Design, Firmware development, PCB designing , testing and prototyping. He enjoys sharing his experience with others .Get in touch with Dost on Twitter or via Contact form


Leave a Reply