Search code examples
androidandroid-viewandroid-custom-view

Programmatically add to AttributeSet in custom View


I've written a custom View that overrides onMeasure() and onLayout() to accomplish a very specific task, ignoring certain attributes like layout_height and layout_width. Since it no longer makes sense to specify those attributes, I want to omit them in my layout XML. But if I do, I get exceptions saying that the attributes are required:

RuntimeException: Binary XML file line #49: You must supply a layout_width attribute.

Is there any way to no longer require certain required attributes?

I was going to try adding those properties programmatically, in my View's constructor, but AttributeSet only seems to have methods for retrieving values, not setting them. I looked into whether I could find a solution using attrs.xml but didn't see anything promising. Ideas?


Solution

  • In order to close out this question, I'll go ahead and summarize the discussion that's gone on so far, along with some additional insights.

    Simply put, layout_width and layout_height should always be set, regardless of whether they are honored by the View they are being set on. Even Views provided by Android that ignore those attributes still require them to be set in the layout XML.

    When a layout is inflated, the custom View is constructed prior to the validation exception being thrown. When I log the class of the AttributeSet provided to my View's constructor, I see that it is an XmlBlock$Parser. I believe I could set a dummy layout_height and layout_width value by casting the AttributeSet and calling setProperty(), allowing validation succeed without specifying those attributes in XML. However, that approach assumes that the AttributeSet provided is always a specific implementation, in all situations and all versions of Android.