【问题标题】:Android: references to findViewByIdAndroid:对 findViewById 的引用
【发布时间】:2016-07-22 11:11:44
【问题描述】:

当我从我的 UI 中引用一个元素时,我一直在为我的所有活动执行此操作,我创建了一个类变量。这有时会导致仅用于 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 是否会失去其点击功能?

我只是在尝试优化应用程序的内存使用。

【问题讨论】:

    标签: java android memory reference findviewbyid


    【解决方案1】:

    第二种方法更节省内存吗?

    不是特别。 LinearLayout addComment 引用大约需要 8 个字节。

    不再有类变量强引用,因此垃圾回收更容易发生

    在这种情况下不是,因为其他东西正在占用LinearLayout。毕竟,findViewById() 正在从某个地方获取LinearLayout

    【讨论】:

    • 谢谢 - 我认为第二种方法更节省内存,实际上是要将我的所有引用更改为看起来像第二种方法。
    • @Simon:好吧,如果您打算稍后使用该字段,只需在字段中保留一个小部件。如果这是使用该字段的唯一位置,请切换到第二种方法或使用局部变量。明显更糟 是不断调用findViewById(),检索相同的小部件。这会产生 CPU 和堆碎片成本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2016-04-15
    相关资源
    最近更新 更多