简体   繁体   中英

what's the benefit of using new Button(this)?

ConditonA:

//declare mybutton object and point to null;
Button mybutton ; 
//mybutton point to the instance of layout_button
mybutton = (Button)findViewByid(R.id.layout_button);

CondtionB:

//declare mybutton object and point to new Button object;
Button mybutton = new Button(this);
//mybutton repoint to the instance of layout_button
mybutton = (Button)findViewByid(R.id.layout_button);
// previous new Button(this) should be recycle??

Hi all
As above example , i found many sample code use Condition B ,but i don't know what's the benefit of it. Should it result in garbage???

When called in an activity, "this" provides the current context, so it is the same thing as doing:

Button = new Button(getContext());

You can use this constructor when you're making a button from scratch. But if you've already declared your button in XML, you can just use findViewByid(R.id.my_button_id_here) instead, which will locate the button already defined in your XML. So in your second example there, you don't need the new Button(this) , because it is being overwritten by the findViewByid statement in the next line.

Here you can see that Android uses findViewByid alone for buttons defined in XML. Here you can see how the context constructor is used to create a button that is not defined in XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM