4

Does LayoutInflater loads xml layout resource every time when we load view using it?

View view = LayoutInflater.from(context).inflate(R.layout.resource, null);

For example, if I want to create 100 views with the same layout id, will it parse 100 times the same XML file or there is some android framework's cache system?

pleerock
  • 18,322
  • 16
  • 103
  • 128

2 Answers2

0

When you look at inflate code flow you can see that multiple caches are evidently used:

I see firstly:

View view = tryInflatePrecompiled(resource, res, root, attachToRoot);

then another cache in ResourceImpl XmlResourceParser loadXmlResourceParser

 @NonNull
    XmlResourceParser loadXmlResourceParser(@NonNull String file, @AnyRes int id, int assetCookie,
            @NonNull String type)
            throws NotFoundException {
        if (id != 0) {
            try {
                synchronized (mCachedXmlBlocks) {
                    final int[] cachedXmlBlockCookies = mCachedXmlBlockCookies;
                    final String[] cachedXmlBlockFiles = mCachedXmlBlockFiles;
Renetik
  • 5,887
  • 1
  • 47
  • 66
-1

I guess yes, It loads 100 times..because every time the same statement gets executed.. That's why we have different adapter and using their getView we create/inflate the view only once and then after just copy paste the same object with different values in it.that we make the viewholder
You too should do something that way.. the if..else in getView method


I was about to post comment but as it become so longer copied as answer , will try to put more code and explanation later, if i got any relevant

MKJParekh
  • 34,073
  • 11
  • 87
  • 98
  • 1
    Seems so too. Ive looked android source and it seems inflate method always iterates XmlPullParser object which retrieves from layout file. And we also can't use the same XmlPullParser instance twice. Fortunately Romain Guy here http://stackoverflow.com/questions/4159211/how-do-i-clone-a-view says that xml parsed very efficiently – pleerock Sep 21 '12 at 07:21
  • Did you really read source code ? – Renetik Oct 03 '22 at 11:34