1

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???

  • Example B is wildly incorrect. Don't use it. You're creating UI elements that are never used. – 323go Sep 09 '15 at 16:36

1 Answers1

2

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.

Community
  • 1
  • 1
Zarwan
  • 5,537
  • 4
  • 30
  • 48