LibGDX can be embedded in an Android application as a Fragment
rather than a complete activity.
From the official documentation:
A libGDX game can be hosted in an Android Fragment instead of using a complete Activity. This allows it to take up a portion of the screen in an Activity or be moved between layouts. To create a libGDX fragment, subclass AndroidFragmentApplication
and implement the onCreateView()
with the following initialization:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return initializeForView(new MyGdxGame());
}
That code depends on some other changes to the -android
project:
- Add AndroidX Fragment Library to the -android project and its build path if you haven't already added it. This is needed in order to extend
FragmentActivity
later.
- Change the
AndroidLauncher
Activity to extend FragmentActivity
, not AndroidApplication
.
- Implement
AndroidFragmentApplication.Callbacks
on the AndroidLauncher
Activity.
- Create a class that extends
AndroidFragmentApplication
which is the Fragment
implementation for libGDX.
- Add the
initializeForView()
code in the Fragment
's onCreateView
method.
- Finally, replace the
AndroidLauncher
activity content with the libGDX Fragment
.
For more examples, see the official documentation or this StackOverflow question.
LibKTX should work seamlessly in a Fragment
, and you should be able to easily translate the examples from Java into Kotlin if you want to.