[英]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??
大家好
如上例所示,我發現許多示例代碼都使用條件B,但我不知道它的好處是什么。 它會導致垃圾嗎???
在活動中調用時,“ this”提供當前上下文,因此與執行此操作相同:
Button = new Button(getContext());
從頭開始制作按鈕時,可以使用此構造函數。 但是,如果您已經使用XML聲明了按鈕,則可以只使用findViewByid(R.id.my_button_id_here)
,它將查找XML中已定義的按鈕。 因此,在第二個示例中,您不需要new Button(this)
,因為下一行的findViewByid
語句將覆蓋它。
在這里,您可以看到Android僅將findViewByid
用於XML定義的按鈕。 在這里,您可以看到如何使用上下文構造函數來創建未在XML中定義的按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.