在Android Studio应用中缓慢加载图像

时间:2018-08-06 13:18:36

标签: android-studio kotlin

嗨,我是一个初学者,我正在学习构建应用程序,我正在使用小型应用程序名称“ roll dice”,但是每当我增加循环大小(例如约100)时,更改图像大约需要12秒钟,所以我希望图像立即更改,例如单击按钮时就像动画一样 我还检查了logcat,并说“将代码缓存容量增加到128kb”(这不是错误消息),我还附加了logcat屏幕截图

 fun rollDice(v: View?)
{
    st=0
    rollresult?.setText("clicked")


       // var no = random!!.nextInt(6) + 1
    while(st<100) {
        dic1 = random!!.nextInt(6) + 1
        dic2 = random!!.nextInt(6) + 1
        dic3 = random!!.nextInt(6) + 1
        dice[0] = (dic1)
        dice[1] = (dic2)
        dice[2] = (dic3)


        // Toast.makeText(applicationContext,"no is "+no,Toast.LENGTH_SHORT).show()
        var diceset = 0
        while (diceset < 3) {

            try {// var string: String = "dice" + dice!![diceset] + ".png"
                var string = "dice" + dice[diceset] + ".png"
                var stream: InputStream = getAssets().open(string)
                var draw: Drawable = Drawable.createFromStream(stream, null)
                var test: ImageView? = diceimageview[diceset]
                test?.setImageDrawable(draw)

            } catch (e: IOException) {
                e.message

            }
            diceset++


        }
        st++
    }



}

1 个答案:

答案 0 :(得分:0)

使用Frame Animation而不是尝试一张一张地加载图像。

为此,您需要将图像移至drawable资源目录,而不是assets目录。然后根据它们创建一个animation-list可绘制资源。

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true">

    <item android:drawable="@drawable/dice1" android:duration="100" />
    <item android:drawable="@drawable/dice2" android:duration="100" />
    <item android:drawable="@drawable/dice3" android:duration="100" />

</animation-list>

然后将动画加载到您的ImageView中。

diceImageView.setBackgroundResource(R.drawable.dice_animation)

最后开始动画。

val diceAnimation = diceImageView.getBackground() as AnimationDrawable
diceAnimation.start()