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  How to play ringtone/alarm/notification sound in Android

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


One thought on “Android: Call to getLayoutInflater() outside activity

  1. Hi,

    i have created a PopupWindow on an inflater.

    i want to dismiss the popup with a custom method by user interaction on a button or performClick of this popup button.

    if i try to get the inflater and check the button with findViewById i have an exception.

    why i can resolve?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.