0

I need to pre load a complex layout so I can show the activity more quickly the first time:

LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

SlowActivity.cachedView = inflater.inflate(R.layout.activity_layout, null, false);

when SlowActivity starts...

public static View cachedView = null; 

@Override
public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
        setContentView(this.cachedView);
      }
}

I can't find where I read it but some one says that I'm doing a memory leak using a stati variable to store inflated layout.

Why?

Maybe I need to release some resource when activity is destroyed (never, it's always put on the background...)

4

2 回答 2

3

那是因为布局,就像所有的视图一样,有一个对持有它的活动的引用。

因此,在 Activity 关闭并应该被释放后,静态变量持有对引用 this Activity 的视图的引用,因此应用程序占用的内存比它应该的要多。

视图不是您应该尽量避免使用静态变量进行缓存的唯一变量。一个例子是drawables,如此处所示

于 2012-07-31T08:35:27.270 回答
1

因为 Android 可以(并且将会)在每次需要内存时销毁您的应用程序/活动(包括静态变量!)。所以你必须考虑一下,什么时候创建静态变量。否则,在应用程序处于非活动状态后,您会变得奇怪且难以发现崩溃。

于 2012-07-31T08:35:51.453 回答