Search code examples
androidserializationviewlifecycle

Android: does custom view not used "from xml" need to have default constructors?


I have a custom view that I always create in code and add to the views hierarchy in code, so it is never included from xml (I know that the next person maintaining my code after may want to use it from xml, but let's assume for the sake of simplicity that this will never happen).

My view does not have the standard constructors ((Contex), (Context, AttributeSet)), my constructor has some extra params. Is this ok? I know the standard constructors would be called when the view is included from XML, but as mentioned above I do not use the view from xml. I have a doubt however what would happen if there is low memory situation, my activity is killed but the view hierarchy preserved - would not those constructors be needed since Android calls them while recreating view instances? I tested that by setting in the simulator to kill activities when I leave them - in spite of lack of those default constructors my app does not crash and the custom view looks normally. My doubt is still there since I do not know how it really works.

In other words my question is: 1. In the situation described above, in what form the view hierarchy is preserved? Is it just serialized? Written to XML? Any other way? 2. When the view hierarchy is resurrected, how the view objects are recreated (Default constructor called? Constructor with Context argument called? Some other way?)

Thanks!


Solution

  • In the situation described above, in what form the view hierarchy is preserved?

    It is not preserved.

    When the view hierarchy is resurrected, how the view objects are recreated

    By however your code creates them.

    does custom view not used “from xml” need to have default constructors?

    You need whatever constructor(s) you are using. Layout inflation requires the two-parameter constructor (Context, AttributeSet), last I checked. But, if you are not using that, you do not need to implement it.