Skip to content
Guillaume Gendre edited this page Jun 6, 2019 · 66 revisions

Adding Cobalt to an Android Project

This page describes how to add Cobalt to an existing Android Project with Android Studio.

Adding Cobalt

Import the Cobalt module into your project:

  • Select File > Import Module...,
  • Browse to the Cobalt directory and then to the Android sources folder <cobalt>/sources/Android/cobalt/ and click Choose,
  • Click Finish to import the module.

Adding global variable for Cobalt and its plugins

In your project build.graddle file, add project.ext as shown below :

allprojects {
    repositories {
        ...
    }

    project.ext {
        buildToolsVersion="28.0.1"
        androidSupportVersion="28.0.0"
        minSdkVersion=19 //Android 4.4.0
        targetSdkVersion=28
        compileSdkVersion=28
    }
}

Adding the Web resources folder

This folder contains the Web side of your app: Web pages, styles, javascript libraries and so on.

By default, this folder is located at <hello>/assets/www, but you can override its path this way:

  • Create an Application class inheriting from android.app.Application,
  • Override the onCreate method and call Cobalt.getInstance(this).setResourcePath("www/"), Cobalt.getInstance(this).setPackageName(getPackageName()),
  • Update the android:name attribute of the application element of your AndroidManifest.xml file to match your Application class name.

Initializing the Web side

Once the Web resources folder is created and added to your project, it is time to make it yours.

Jump to the Web Setup page and come back later ;-).

Loading your first HTML page

Welcome back! Now that you have configured Cobalt and added your Web resources, you have to create all your Activity classes referenced in the cobalt.json file.

For each activity meant to be hybrid:

  • Inherit it from CobaltActivity,
  • Create the attached Fragment class inheriting from CobaltFragment,
  • Update the overriden getFragment() method of the activity to return a new instance of the attached fragment (see below).

For common activities:

@Override
protected CobaltFragment getFragment() {
    return new MainFragment();
}

For the activity started at app launch:

@Override
protected CobaltFragment getFragment() {
    return Cobalt.getInstance(this).getFragmentForController(MainFragment.class, "default", "index.html");
}

Then, you must declare these activities in your AndroidManifest.xml file in the application element (see below).

<activity android:name="com.example.Hello.MainActivity" />

For the activity started at app launch, you must add these lines in the activity element:

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

Enabling logging

If you want to enable logging, you just have to set Cobalt.DEBUG to true which is set to false by default.

Clone this wiki locally