public View findViewById(int id) { return getWindow().findViewById(id); }
和getWindow方法的定义:
public Window getWindow() { return mWindow; }
但是按照以下规则:
Avoid Internal Getters/Setters
In native languages like C++ it’s
common practice to use getters (e.g. i
= getCount()) instead of accessing the field directly (i = mCount). This is
an excellent habit for C++,because
the compiler can usually inline the
access,and if you need to restrict or
debug field access you can add the
code at any time.On Android,this is a bad idea.
Virtual method calls are expensive,
much more so than instance field
lookups. It’s reasonable to follow
common object-oriented programming
practices and have getters and setters
in the public interface,but within a
class you should always access fields
directly.Without a JIT,direct field access is
about 3x faster than invoking a
trivial getter. With the JIT (where
direct field access is as cheap as
accessing a local),direct field
access is about 7x faster than
invoking a trivial getter. This is
true in Froyo,but will improve in the
future when the JIT inlines getter
methods.
所以我想知道为什么android开发人员不能直接访问这个mWindow对象?如果当前Android版本的JIT无法内联访问,则getWindow().findViewById(id)将比mWindow.findViewById(id)花费更多时间,而findViewById是一种相当常用的方法.
解决方法
而且我不关心findViewById的速度,因为您只需要在onCreate()方法中为布局中的每个视图调用一次,并将视图存储在活动成员中.你每个视图只调用一次findViewById,不是吗?