java - Android:对 findViewById 的引用

标签 java android memory reference findviewbyid

当我从我的 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/

相关文章:

java - 数组和链表: will arrays be able to allocate 300MB in memory if 512 MB is free but 300 MB is not contiguous

testing - STREAM 基准的向量函数

c# - 固定缓存的哈希表大小

java - 为什么我的程序不输出数组元素?

java - 如何获得 for 循环中所有项目的总金额?

android - 如何在Kotlin中删除ClipboardManager的OnPrimaryClipChangedListener?

android - SMSManager 不适用于三星 Galaxy S3 LTE

android - 为什么 Android 收不到 FCM 推送通知?

java - 有没有办法以二进制形式显示 float ?

java - 如何从 Java 程序动态创建新的 .java 文件?