问题描述
我正在开发一个由 Fragment 组成的应用程序(只有一个 Activity),我想要一个移动的背景,它目前由一个 AnimationDrawable
组成。它工作正常,但问题是使用了高达 0.9GB 的内存......我想减少它。
当前代码(activity_main.xml
):
<FrameLayout 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:id="@+id/contentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background_animation" />
而 background_animation.xml
是:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@drawable/background_frame_01" android:duration="42" />
<item android:drawable="@drawable/background_frame_02" android:duration="42" />
... // continues for 96 more frames
</animation-list>
所以,我想将一个 View 子类化并将它放在后面的任何地方......就像这样:
class BackgroundView(context: Context,attrs: AttributeSet) : View(context,attrs) {
private val frames = arrayOf(
resources.getDrawable(R.drawable.background_frame_01),resources.getDrawable(R.drawable.background_frame_02),/* continues for 96 more frames */ )
private val length = frames.lastIndex // 97
private val DELTA_TIME = 42 // draw next frame every 42ms
private var i = 0
private var currentFrame: Drawable
private var lastRenderTime: Long? = null
init {
currentFrame = frames[0]
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (lastRenderTime == null || System.currentTimeMillis() - lastRenderTime!! >= DELTA_TIME) {
currentFrame = frames[i]
currentFrame.setBounds(0,width,height)
currentFrame.draw(canvas)
i++
if (i > length) i = 0
lastRenderTime = System.currentTimeMillis()
}
invalidate()
}
}
然后 activity_main.xml
变成了这个:
<FrameLayout 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:id="@+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<BackgroundView
android:id="@+id/backgroundView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<FrameLayout
android:id="@+id/contentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
我可以看到移动的背景,但是,屏幕以非常高的速度闪烁,这绝对是我不想要的。我该如何解决这个问题?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)