Call getLayoutInflater() in places not in activity

AndroidServiceAndroid ContextToastLayout Inflater

Android Problem Overview


What does need to be imported or how can I call the Layout inflater in places other than activity?

public static void method(Context context){
    //this doesn't work the getLayoutInflater method could not be found
    LayoutInflater inflater = getLayoutInflater();
    // this also doesn't work 
    LayoutInflater inflater = context.getLayoutInflater();
}

I am able to call getLayoutInflater only in activity, is that an restriction? What if I want to create custom dialog and I want to inflate view for it, or what if I want to have Toast message with custom view that is shown from a service, I only have the context from the service I do not have any activity but I want to show custom message.

I need the inflater in places in the code that isn't in the activity class.

How can I do this ?

Android Solutions


Solution 1 - Android

You can use this outside activities - all you need is to provide a Context:

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( R.id.myButton );

EDIT as of July 2014

Davide's answer on how to get the LayoutInflater is actually more correct than mine (which is still valid though).

Solution 2 - Android

Or ...

LayoutInflater inflater = LayoutInflater.from(context);

Solution 3 - Android

or

View.inflate(context, layout, parent)

Solution 4 - Android

Using context object you can get LayoutInflater from following code

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

Solution 5 - Android

LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);

Solution 6 - Android

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

Use this instead!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLukapView Question on Stackoverflow
Solution 1 - AndroidkaspermoerchView Answer on Stackoverflow
Solution 2 - AndroidDavideView Answer on Stackoverflow
Solution 3 - AndroidPrakash NadarView Answer on Stackoverflow
Solution 4 - AndroidanujprasharView Answer on Stackoverflow
Solution 5 - AndroidSikander BakhtView Answer on Stackoverflow
Solution 6 - Androiduser10327345View Answer on Stackoverflow