Android Kotlin阵列太大?内部编译器错误

Android Kotlin阵列太大?内部编译器错误,android,kotlin,Android,Kotlin,我创建了一个应用程序,每次启动应用程序时都会显示一个随机图像 一切正常,但由于包含可绘制路径的数组包含大约6000多个项目,因此我在构建APK时出错 数组是否仅限于一定数量的项目,是否有其他方法 MainActivity.kt package com.example.randomimages import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthe

我创建了一个应用程序,每次启动应用程序时都会显示一个随机图像

一切正常,但由于包含可绘制路径的数组包含大约6000多个项目,因此我在构建APK时出错

数组是否仅限于一定数量的项目,是否有其他方法

MainActivity.kt

package com.example.randomimages

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import kotlin.random.Random


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val images = arrayOf(
            R.drawable.image1,
            // ...
            R.drawable.image8829
        )


        image1.setImageResource(images[Random.nextInt(images.size)])
    }
}
活动\u 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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/image1"
        tools:layout_editor_absoluteX="121dp"
        tools:layout_editor_absoluteY="219dp" />
</androidx.constraintlayout.widget.ConstraintLayout>

实际的错误消息是:

方法太大:com/example/randomimages/main活动。onCreate

有两种可能的方法,它们都比你的方法更少滥用:


A) 将
val图像
移动到:


B) 理想情况是,在参考资料中将其定义为
数组

<array name="images">
    <item>@drawable/image1</item>
    <item>@drawable/...</item>
    <item>@drawable/image8829</item>
</array>

@可绘图/图像1
@可提取/。。。
@可绘图/图像8829
与此类似,阵列可以在任何地方访问,而不仅仅是在
MainActivity

此外,应该很快就能设置映像
.onCreateView()

class MainActivity : AppCompatActivity() {

    ...

    companion object Images {
        val items = arrayOf(
            R.drawable.image1,
            // ...
            R.drawable.image8829
        )
    }
}
<array name="images">
    <item>@drawable/image1</item>
    <item>@drawable/...</item>
    <item>@drawable/image8829</item>
</array>