måndag 13 juli 2015

Running jMonkeyEngine 3 on Android using AndroidHarnessFragment

There's a new way of running jMonkeyEngine 3 on Android, using fragments. Since I couldn't find a description of how to do it or a use case, I thought I'd write down how I did.
The old (and still functional) used a class called AndroidHarness that extended Activity and contained all the app specific information in it. This post describes how to use the new AndroidHarnessFragment.
  • First of all, AndroidHarnessFragment contains a lot of app-specific settings. The most important of these are appClass, which is a String containing the qualified name of the Application to run. This and a lot of other fields are protected and it seems the intended way of using the class is by extending it. This way you can set all of them in the constructor of the new class, even if there are other ways more aligned with Android conventions (such as using a Bundle).
  • Previously the auto-generated MainActivity class extended AndroidHarness. Now it should just extend Activity.
  • To create the fragment, we can create a layout file for the activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<fragment android:name="com.mycompany.mygame.MyAndroidHarnessFragment"
android:id="@+id/app_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
  • Finally we tell MainActivity to use the layout file we just created.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
That's all that seems to be needed to run jMonkeyEngine inside a fragment!