How does AppCompat inflate layouts that do not explicitly use AppCompat widgets?

半城伤御伤魂 提交于 2020-12-12 06:50:47

问题


It occurred to me while using AppCompat, that I had been using things like Button instead of android.support.v7.widget.AppCompatButton within my layout XML files. I did a test, via view.getClass().getSimpleName() and confirmed that even though I declared it as a Button in the XML, the class being loaded was in fact AppCompatButton.

How does this work, under the hood?


回答1:


In the process of researching this topic in order to ask the question correctly, I discovered the answer myself.

When using AppCompatActivity, some interesting things happen:

  1. A LayoutInflater.Factory is applied to the default LayoutInflater, via setFactory. The AppDelegateImpl classes within AppCompat implement the Factory interface, and one of them is chosen as the factory delegate depending on the API level. There is also a slightly different Factory2, targeting later APIs.
  2. When your views are being inflated from XML, the name of the view's class is passed into the Factory's createView method, which is given the opportunity to override the actual view that is created.
  3. The name of the view is checked against a hard-coded hash table of strings in AppCompatViewInflater, and if a match is found the view is inflated by the delegate, instead of the default inflater.


来源:https://stackoverflow.com/questions/54575093/how-does-appcompat-inflate-layouts-that-do-not-explicitly-use-appcompat-widgets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!