drhodes
drhodes

Reputation: 41

How would I convert an Android XML layout to a Java class?

Here is what I'm trying to do:

I want to create a JAR to be included in Android apps that contains views and images. As far as I know, you can't package the res folders in a JAR. So what I am looking to do is convert the XML files in my res folder to an Android view class, which I can then compile as part of the project into the JAR.

Are there any tools or projects which have done this successfully? Alternative solutions are also welcome.

Upvotes: 2

Views: 1298

Answers (3)

Femi
Femi

Reputation: 64700

I had this exact issue: wanting to distribute my library as a jar file. A reasonable number of support issues were caused by people just not being familiar with the library project bits (shocking to me, but who am I to argue).

First, there was really no support for automatically generating java classes from XML layouts. I'd thought that I could perhaps extract the source code used by the ADT to render your XML layouts into separate classes, but after futzing around with that for a couple of hours I gave up and wrote the layouts out by hand. Make them extend RelativeLayout and build the hierarchy in code. Works, but doesn't quite scale. At some point it may be worth digging into the ADT source to allow you to export a layout.

For images I restricted it to just icons, then wrote an ugly little tool that would generate a byte[] array from the PNG files and then adds that as a static final variable in a separate class for each image: you're limited to small images, I think less than 40k or some unknown part of the Android build process craps out because the generated class files are too large. Once that is done I can reconstitute the images in my view classes using code like this:

audio_icon = new BitmapDrawable(BitmapFactory.decodeByteArray(AudioIcon.bytes, 0, AudioIcon.bytes.length));

I have a package for all the icons, and it actually worked pretty well. You do give up the customization options offered by the library format, but it has made our integration process real simple.

Upvotes: 0

StoneBird
StoneBird

Reputation: 1940

Do this:

public class MyView extends View{
    private TextView tv; //or other elements in the layout you want
    //here also has constructors
    @Override
    public void onDraw(Canvas canvas){
        //draw the views that you prepared in your constructor
    }
}

If you extend LinearLayout it would be LinearLayout in XML, extends RelativeLayout then be RelativeLayout etc. All these layouts are subclasses of View.

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93561

You can make every view in it dynamically and set the appropriate setting- every setting in xml has a matching Java call to change. That doesn't fix anything other than the layouts folder though. It would be far easier to give them the code as an Android library project.

Upvotes: 1

Related Questions