Is there a way to create a custom XML data type for Android?
I have a class Model that contains all of the statistics of my entities. I want to be able to inflate Model class from xml similar – well, exaclty as View’s do. Is this possible?
Example:
<?xml version="1.0" encoding="utf-8"?>
<models xmlns:android="http://schemas.android.com/apk/res/android">
<model name="tall_model"
type="@string/infantry"
stat_attack="5"
>Tall Gunner</model>
<model name="short_model"
type="@string/infantry"
stat_attack="3"
ability="@resource/scout"
>Short Gunner</model>
<model name="big_tank"
type="@string/vehicle"
stat_attack="7"
armour="5"
>Big Tank</model>
</models>
And the class I would like to inflate.
class Model [extends Object] {
public Model(Context context, AttributeSet attrs) {
// I think you understand what happens here.
}
// ...
}
With some custom code using carefully selected APIs, you can mimic the way Android inflates layout XML files and still benefit from the XML optimizations and goodies that Android has like compiled XML files and references to arbitrary resources within your custom XML files. You can’t directly hook in into the existing
LayoutInflaterbecause that class can only deal with inflatingViews. In order for the below code to work, put your XML file in ‘res/xml’ in your application.First, here’s the code that parses the (compiled) XML file and invokes the
Modelconstructor. You might want to add some registering mechanism so that you can easily register a class for any tag, or you might want to useClassLoader.loadClass()so that you can load classes based on their name.With this in place, you can put the “parsing” of the attributes inside the
Modelclass, much likeViewdoes it:Above I have referenced attributes through the string representation. If you want to go further, you can define application specific attribute resources and use those instead, but that will complicate things quite a bit (see Declaring a custom android UI element using XML). Anyway, with all resources setup and this in a dummy activity:
you’ll get this output:
Note that you can’t have
@resource/scoutin your XML file sinceresourceis not a valid resource type, but@string/fooworks fine. You should also be able to use for example@drawable/foowith some trivial modifications to the code.