可以是静态的参考查看内存泄漏?静态、内存

2023-09-06 05:29:18 作者:没事抽风儿

我是真正的新Android开发,我已经了解避免条内存泄漏的Andr​​oid平台。我不知道,如果我的下面code ...

I am really new to Android development and I have read article about Avoiding Memory Leaks on Android platform. I am not sure, if my following code...

public class TransactionDetailActivity extends Activity {

private Transaction transaction;

private TextView tvDetail; //static reference

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.screen_transaction_detail);

    tvDetail = (TextView) findViewById(R.id.detail); //init of reference
}

本存储到静态引用可导致开关以外的活动屏幕旋转后的内存泄漏?如果是,我怎么能避免呢?

Can this storing into static reference cause any memory leaks after screen rotation on switching other Activities? If YES, how can I avoid it?

非常感谢您的帮助!

推荐答案

私人TextView的tvDetail; 不是一个静态的参考。

private TextView tvDetail; is not a static reference.

私有静态的TextView tvDetail; 是一个静态的参考,但它是不可取的。这里有一个解释:http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html

private static TextView tvDetail; is a static reference, but it's not desirable. Here you have an explanation: http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html

有时,我们的开发人员设置变量为静态的,以避免重新创建对象......这样的事情在你的情况下:

Sometimes, we developers set variables as static to avoid recreating objects... something like this in you case:

// DON'T DO THIS! FOR THE LOVE OF GOD! 
if( tvDetail == null ){
    tvDetail = (TextView) findViewById(R.id.detail);
}

但是,这是错误的android开发,每个的onCreate 方法被调用的时间,因为,在创建UI元素的新引用过。所以,只是尽量避免code以上。

But this is wrong in android development, since each time the onCreate method is called, new references to the UI elements are created too. So, just try to avoid the code above.