Jad Salhani Jad Salhani - 3 months ago 57
Android Question

Change android theme from cordova config.xml

At my company we are using Ionic Framework and Cordova to create our mobile app, and upon starting the design of the app, we encountered an issue with the Android theme and how to set it without touching the AndroidManifest generated by Ionic build command.

Everywhere I look it is recommended to implement any customization from the config.xml file and never touch the AndroidManifest, but I cant seem to find any methods regarding the Android theme.

My question to you now: Is there a way to set the android theme for the application, for example Holo Theme, from the Config.xml without changing the AndroidManifest.xml generated?

Answer

To avoid touching the platforms directory, you could use a cordova hook. I am pretty terrible at node, but here is something that should do the trick. First npm install elementtree then create a sub folder after_prepare in the hooks folder. From there stick this code into a javascript file and change YourTheme.

Honestly, this is some pretty gross code, but should give you the idea.

#!/usr/bin/env node
var fs = require( "fs" );
var et = require('elementtree');
var rootdir = process.argv[2];
console.log(rootdir);
fs.open(rootdir + '/platforms/android/AndroidManifest.xml', 'r+',
    function (err, fd)  {
        if (err) {
            exitError(err);
        }
        fs.stat(rootdir + '/platforms/android/AndroidManifest.xml', getStats);

        function getStats(error, stats) {
            if (error) {
                exitError(error);
            }
            var buffer = new Buffer(stats.size);
            fs.read(fd, buffer, 0, buffer.length, null, fileRead);
        }

        function fileRead(error, bytes, buf) {
            var data = buf.toString("utf8", 0, buf.length);
            var androidXML = et.parse(data);
            var root = androidXML.getroot();
            var activityTag = root.find("application/activity");
            activityTag.attrib["android:theme"] = "@style/YourTheme";
            var outputBuffer = new Buffer(et.tostring(root), "utf-8");
            console.log(outputBuffer.toString());
            fs.closeSync(fd);
            fs.open(rootdir + '/platforms/android/AndroidManifest.xml', 'w', writeFile);
            function writeFile(error, fd) {
                if (error) {
                    exitError(error);
                }
                fs.write(fd, outputBuffer, 0, outputBuffer.length, 0, function( errw, written, str) {
                    if (errw) {
                        exitError(errw);
                    }
                    console.log('file written');
                    fs.close(fd);
                });
            }

        }
    });

function exitError(error) {
    console.log(error);
    process.exit(0);
}
Comments