Java 什么';使用新按钮(这个)有什么好处?

Java 什么';使用新按钮(这个)有什么好处?,java,android,Java,Android,条件: //declare mybutton object and point to null; Button mybutton ; //mybutton point to the instance of layout_button mybutton = (Button)findViewByid(R.id.layout_button); //declare mybutton object and point to new Button object; Button mybutton = ne

条件:

//declare mybutton object and point to null;
Button mybutton ; 
//mybutton point to the instance of layout_button
mybutton = (Button)findViewByid(R.id.layout_button);
//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??
条件b:

//declare mybutton object and point to null;
Button mybutton ; 
//mybutton point to the instance of layout_button
mybutton = (Button)findViewByid(R.id.layout_button);
//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??
大家好

正如上面的例子,我发现许多示例代码使用条件B,但我不知道它有什么好处。它是否会导致垃圾???

在活动中调用时,“this”提供当前上下文,因此它与执行以下操作相同:

Button = new Button(getContext());
当您从头开始制作按钮时,可以使用此构造函数。但是,如果您已经在XML中声明了按钮,那么您可以使用
findViewByid(这里是R.id.my\u button\u id)
,它将定位已经在XML中定义的按钮。因此,在第二个示例中,您不需要使用
new按钮(this)
,因为它正在被下一行中的
findViewByid
语句覆盖

您可以看到,Android单独使用
findviewbyd
作为XML中定义的按钮。
您可以看到如何使用上下文构造函数创建未在XML中定义的按钮。

示例B完全不正确。不要用它。您正在创建从未使用过的UI元素。
findViewById
不是构造函数。@323go这是真的,我不知道我称它为构造函数。修好了,谢谢。