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 );
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()
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?