LibGDX: только для Android.
Научимся использовать: AndroidFragmentApplication.
GIT: https://github.com/Vladislav-Shesternin/LibGDX-only-Android.git
- Создаём проэкт в AndroidStudio.
- Заполняем build.gradle(app):
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.veldan.libgdx" // Change to your package name
minSdk 21
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
sourceSets {
main {
jniLibs.srcDirs = ['libs']
assets.srcDirs 'src\\main\\assets'
}
}
viewBinding.enabled = true
}
configurations { natives }
dependencies {
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
def gdx_version = '1.10.0'
api "com.badlogicgames.gdx:gdx-backend-android:$gdx_version"
natives "com.badlogicgames.gdx:gdx-platform:$gdx_version:natives-armeabi-v7a"
natives "com.badlogicgames.gdx:gdx-platform:$gdx_version:natives-arm64-v8a"
natives "com.badlogicgames.gdx:gdx-platform:$gdx_version:natives-x86"
natives "com.badlogicgames.gdx:gdx-platform:$gdx_version:natives-x86_64"
def core_version = '1.7.0'
implementation "androidx.core:core-ktx:$core_version"
def appcompat_version = '1.3.1'
implementation "androidx.appcompat:appcompat:$appcompat_version"
def material_version = '1.4.0'
implementation "com.google.android.material:material:$material_version"
def constraintLayout_version = '2.1.1'
implementation "androidx.constraintlayout:constraintlayout:$constraintLayout_version"
def navigation_version = '2.3.5'
implementation "androidx.navigation:navigation-fragment-ktx:$navigation_version"
}
task copyAndroidNatives {
doFirst {
file("libs/armeabi/").mkdirs()
file("libs/armeabi-v7a/").mkdirs()
file("libs/arm64-v8a/").mkdirs()
file("libs/x86_64/").mkdirs()
file("libs/x86/").mkdirs()
configurations.natives.copy().files.each { jar ->
def outputDir = null
if (jar.name.endsWith("natives-arm64-v8a.jar")) outputDir = file("libs/arm64-v8a")
if (jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a")
if (jar.name.endsWith("natives-armeabi.jar")) outputDir = file("libs/armeabi")
if (jar.name.endsWith("natives-x86_64.jar")) outputDir = file("libs/x86_64")
if (jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86")
if (outputDir != null) {
copy {
from zipTree(jar)
into outputDir
include "*.so"
}
}
}
}
}
tasks.whenTaskAdded { packageTask ->
if (packageTask.name.contains("package")) {
packageTask.dependsOn 'copyAndroidNatives'
}
}
task run(type: Exec) {
def path
def localProperties = project.file("../local.properties")
if (localProperties.exists()) {
Properties properties = new Properties()
localProperties.withInputStream { instr ->
properties.load(instr)
}
def sdkDir = properties.getProperty('sdk.dir')
if (sdkDir) {
path = sdkDir
} else {
path = "$System.env.ANDROID_HOME"
}
} else {
path = "$System.env.ANDROID_HOME"
}
def adb = path + "/platform-tools/adb"
commandLine "$adb", 'shell', 'am', 'start', '-n', 'com.veldan.libgdx/com.veldan.libgdx.AndroidLauncher' // Change to your package name
}
Обратите внимание на 2 строчки:
1:
defaultConfig {
applicationId "com.veldan.libgdx"
}2:
{‘com.veldan.libgdx/com.veldan.libgdx.AndroidLauncher’}
Вместо com.veldan.libgdx должно быть указано имя Вашего пакета.
3. Добавляем assets, тут будут хранится Наши ресурсы.
4. Создайте 2 класса: LibGDXFragment и LibGDXGame:
LibGDXFragment:
class LibGDXFragment : AndroidFragmentApplication() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val conf = AndroidApplicationConfiguration().apply {
useAccelerometer = false
useCompass = false
}
return initializeForView(LibGDXGame(), conf)
}
}
LibGDXGame:
class LibGDXGame : ApplicationAdapter() {
var batch: SpriteBatch? = null
var img: Texture? = null
override fun create() {
batch = SpriteBatch()
img = Texture("badlogic.jpg")
}
override fun render() {
ScreenUtils.clear(1f, 0f, 0f, 1f)
batch!!.begin()
batch!!.draw(img, 0f, 0f)
batch!!.end()
}
override fun dispose() {
batch!!.dispose()
img!!.dispose()
}
}
5. Создайте навигационный граф:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_graph"
app:startDestination="@id/libGDXFragment">
<fragment
android:id="@+id/libGDXFragment"
android:name="com.veldan.libgdx.LibGDXFragment"
android:label="LibGDXFragment" />
</navigation>
6. Создайте activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>
7. Создайте AndroidLauncher:
lateinit var activityContext: Activity private set
lateinit var navController: NavController private set
class AndroidLauncher : FragmentActivity(), AndroidFragmentApplication.Callbacks {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
activityContext = this
navController = findNavController(R.id.nav_host_fragment)
}
override fun exit() {
finish()
}
}
Поздравляю Вас, можете себе похлопать, Мы справились и можем запустить Android приложение с использованием LibGDX.
Дальше творите как с обычным LibGDX проэктом, создавайте Screen классы и перемещайтесь между ними, стартуйте с класса LibGDXGame.
PS. Vel_daN: Love what You DO 💚.