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

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

 

2 thoughts on “Android: Call to getLayoutInflater() outside activity

  1. Using context object you can get LayoutInflater from following code:

    Java:
    LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)

    Kotlin:
    val layoutInflater = applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

    for kotlin eg:
    //………………custom toast
    val layoutInflater = applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    val toastLayout = layoutInflater.inflate(R.layout.toast_exit, null)
    val toast = Toast(applicationContext)
    toast.view = toastLayout
    toast.duration = Toast.LENGTH_SHORT
    toast.show()

  2. 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.