gpt4 book ai didi

android - Android中的代码解释

转载 作者:行者123 更新时间:2023-11-30 02:40:43 25 4
gpt4 key购买 nike

在我的应用程序中的每个 onDestroy 中,我都在 View 上调用它,因为我读到它是最小化 OOM 异常的好习惯。

    public void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}

问题是,我不太清楚是什么

view.getBackground().setCallback(null) 确实如此。让它这样就够了吗,还是我也应该回收 View 背景的位图?

最佳答案

第一部分 - 要解释 setCallback(null) 的作用,您应该看看“回调”指的是什么。

Drawable.Callback 用于为可绘制对象设置动画。根据在线文档:

Implement this interface if you want to create an animated drawable that extends Drawable. Upon retrieving a drawable, use setCallback(android.graphics.drawable.Drawable.Callback) to supply your implementation of the interface to the drawable; it uses this interface to schedule and execute animation changes.

您可以通过设置为 null 来阻止任何进一步的动画回调。这将删除 Drawable 将包含的对 Callback 对象的所有引用。

如果不删除这些引用,则在解除绑定(bind)可绘制对象时可能会泄漏内存。


第二部分——你应该在这次调用后回收你的位图吗?是的。此调用会删除您的 Activity View 和可绘制对象之间的链接,但不会回收可绘制对象使用的内存。

如果您正在为 2.3 及以下版本编写,您应该回收位图。请参阅 Managing Bitmap Memory 上的页面:

On Android 2.3.3 (API level 10) and lower, using recycle() is recommended. If you're displaying large amounts of bitmap data in your app, you're likely to run into OutOfMemoryError errors. The recycle() method allows an app to reclaim memory as soon as possible.


我看到这段代码在许多其他问题中都有使用,其中一些讨论可能会对 future 的读者有所帮助:

关于android - Android中的代码解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25785937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com