I want to create a custom View, such that when it is inflated with wrap_content as one of the dimension parameters and match_parent as the other, it will have a constant aspect ratio, filling whichever dimension is set to match_parent, but providing the layout inflater with the other dimension to be “wrapped”. I presume this is possible because, for example, a full screen width TextView would obviously be able to demand that it have space for two, three or any arbitrary number of lines of text (depending on width), but would not necessarily know this until inflation-time.
Ideally what I want to do is override layout methods in the View subclass such that when the view is inflated, I get the layout information, and supply my own dimensions for the “content” to be wrapped (ie my fixed-ratio rectangle).
I will need to create a lot of these custom views and put them in various different types of layout—sometimes using an Adapter—so really I want to have the maximum control over their inflation I can. What’s the best technique for doing this?
I’ve now solved this with the following code. It’s worth mentioning in passing that the class I’m overriding is a custom
ViewGroupwith custom children, all using the inheritedonMeasure. The children are created and added at construction-time, and I would assume as a matter of course that this is necessary.I’m defining the aspect ratio in terms of a nominal rectangle in resources, but obviously there are plenty of other ways to do this.
With thanks to Josephus Villarey who pointed me at
onMeasure(...)in the first place.