Can be static reference to View memory leak?

2019-05-24 10:33发布

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?

Thanks a lot for any help!!!

1条回答
在下西门庆
2楼-- · 2019-05-24 10:56

private TextView tvDetail; is not a static reference.

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);
}

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.

查看更多
登录 后发表回答