是否需要在Activity生命周期中每次都调用findViewById? [英] Is it good to call findViewById every time in Activity lifecycle whenever required?

查看:77
本文介绍了是否需要在Activity生命周期中每次都调用findViewById?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当需要引用窗口小部件时,就使用findByViewById.

Whenever we need a reference to the widget, we uses findByViewById.

当我们在同一Activity类的代码中多次引用窗口小部件时,可以采用以下两种方法之一:

When we are referring the widget lots of time in the code of the same Activity class, we can follow either of the approach:

  1. 在活动"生命周期中每次都调用findViewById.
  2. 第一次获取,将引用存储为Activity类的私有实例变量.

哪种方法更好?就性能和内存而言,每种方法的利弊是什么.请帮忙.

Which approach is beter? What would be pros and cons of each approach in terms of performance and memory. Please help.

如果我们从A移到B,则无法完成A,因为我们想在按下时打开A.在这种情况下如何解决以上问题?请帮忙.

If we move to new activity from A to B, we do not finish A as we want to open A on pressing back. In this scenario how to approach above problem? Please help.

推荐答案

两种方法都有其风险.通常,应该在较少的时间内调用findViewById(),另一方面,将引用存储在Activity类上可能会导致内存泄漏.它在很大程度上取决于您想要做什么,您调用它多少次并基于它选择一种方法.为此,您需要分析您的代码,如果您不清楚哪种更好,请尝试两者并选择不太糟糕",但是通常,第一种方法比第二种方法更糟糕,因为您知道自己始终必须查找定义了ID的所有元素.

Both approaches have their risks. In general, you should call findViewById() the less times you can, by the other hand, storing a reference on the Activity class may lead to memory leaks. It depends so much on what you want to do, how much times are you calling it and basing on it choose one of the approaches. For that, you'll need to analyze your code and if you're not clear about which is better, just try both and choose the "less bad", but generally the first approach is worse than the second one because you know you'll always have to find across ALL elements you've defined an id.

这篇关于是否需要在Activity生命周期中每次都调用findViewById?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆