java使用新按钮(这个)有什么好处?
条件:
//declare mybutton object and point to null;
Button mybutton ;
//mybutton point to the instance of layout_button
mybutton = (Button)findViewByid(R.id.layout_button);
条件b:
//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,但我不知道它有什么好处。它会导致垃圾吗
# 1 楼答案
在活动中调用时,“this”提供当前上下文,因此与执行以下操作相同:
当您从头开始制作按钮时,可以使用此构造函数。但是,如果您已经在XML中声明了按钮,那么可以使用
findViewByid(R.id.my_button_id_here)
,它将定位已经在XML中定义的按钮。因此,在第二个示例中,您不需要new Button(this)
,因为它正在被下一行的findViewByid
语句覆盖Here您可以看到Android单独使用
findViewByid
作为XML中定义的按钮。 Here您可以看到如何使用上下文构造函数创建未在XML中定义的按钮