开发者

May I store View objects in instance fields?

I've got an Activity class. It should be really nice to find all the views I need in onCreate, and then just reference these fields, without calling findViewById. But is it OK to do so?

Can't views be assigned different objects at runtime? E.g., is it always tru开发者_Go百科e that findViewById(res1) == findViewById(res1) at any time?


You can create instance variables for your views in an Activity. And

findViewById(res1) == findViewById(res1)

is true as long as the layout is not inflated again or other changes (replacing views) are made to the content view.

But do not keep references to views in objects that will live longer than the activity holding the views. Like in an Singleton! (see see Avoiding Memory Leaks)


Yes you can do this. This is how I've seen it done 90% of the time at my work. Ex.

private ImageView mSomeImage;

public class activ extends Activity{

public void onCreate(Bundle saveinstancestate){
    Inialize your views here.
}

}

Only do this if you need to, and prefix member variables with m.

Does this help?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜