Does an inflatable system require an activity context?

I sometimes add a link to LayoutInflateron Dagger and create it in a module of the application context as follows: LayoutInflater.from(application);. It reduces the number of lines of code.

But colleges tell me that this is the wrong way, and it should be set from the context of activity LayoutInflater.from(MainActivity.this);

It's true? Does the behavior of the inflatable layout affect the type of context?

+4
source share
4 answers

Yes it's true. There is a big difference, given the styles.

LayoutInflaterCreates views by invoking their constructors. There he conveys the context that you conveyed to him. Therefore, if you use the application context instead of the activity context, you may be missing some information.

, . , .

, , . Internal LayoutInflater.cloneInContext(Context) .

LayoutInflater , Context, . ContextThemeWrapper LayoutInflater Context.

.

+2

, LayoutInflater . . .

:

Object[] args = mConstructorArgs;
args[1] = attrs;

constructor.setAccessible(true);
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
    // Use the same context when inflating ViewStub later.
    final ViewStub viewStub = (ViewStub) view;
    viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;

, ( ) View. , , .

+1

, inflater , . , , .

+1
source

you can use getApplicationContext()it when you know that you need a context for something that can live longer than any other likely context that you have at your disposal, for example services.

So, it is better to use activity contextwhen you do not need your object, which will be stored for a long time or on a global scale.

Hope this helps.

0
source

Source: https://habr.com/ru/post/1655284/


All Articles