当我从我的 UI 引用一个元素时,我一直在为我的所有 Activity 执行此操作,我创建了一个类变量。这有时会导致仅用于 UI 元素的 10 - 20 个类变量:
public class CommentActivity extends AppCompatActivity {
LinearLayout addComment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment);
addComment = (LinearLayout) findViewById(R.id.addcomment);
addComment.setOnClickListener( // add an onclick listener here //);
}
}
现在,我通过查看其他人的代码观察到有时他们会这样做:
public class CommentActivity extends AppCompatActivity {
// LinearLayout addComment; no more reference to class variable
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment);
//they just findViewById and add on the onclick listener
findViewById(R.id.addcomment).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
第二种方法内存效率更高吗?不再有类变量强引用,因此垃圾收集更容易发生。但我只是想知道使用第二种方法的风险是什么。如果在使用该应用程序时发生垃圾回收,addComment linearLayout
是否会失去其点击功能?
我只是在尝试优化应用内存使用的方法。
最佳答案
Is the second method more memory efficient?
没有特别的。 LinearLayout addComment
引用占用大约 8 个字节。
There is no longer a class variable strong reference and therefore garbage collection can happen more easily
在这种情况下不是,因为其他东西在 LinearLayout
上。毕竟,findViewById()
是从某处获取 LinearLayout
。
关于java - Android:对 findViewById 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36376764/