2011-09-25 45 views
0

我注意到有兩種方法可以將LayoutParams以編程方式添加到任何視圖,並且好奇地問他們是否也有不同的含義。Android不同的方式來添加LayoutParams

示例1

在此示例中,將LayoutParams直接設置爲按鈕。

LinearLayout parent = new LinearLayout(this); 
Button btnNew = new Button(this); 
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); 
button.setLayoutParams(params); 
parent.addView(btnNew); 

實施例2

在這個例子中,當它被添加到父視圖添加到的LayoutParams按鈕。

LinearLayout parent = new LinearLayout(this); 
Button btnNew = new Button(this); 
LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); 
parent.addView(btnNew, params); 

兩者有什麼不同?

+0

沒有區別,要拆分例2的最後一行中最後兩行例1中。 –

+0

只是在示例1中多了一行。就是這樣。 –

+0

感謝您讓我知道 – Neutralizer

回答

0

沒有區別。如果您檢查了android源代碼,它指定如果沒有指定佈局參數,則設置視圖組的defualts參數。當您使用方法

addView(child,params); 

它調用另一個名爲addViewInner的方法,它只是將params對象設置爲子對象。

ViewGroup.java的源代碼可以在這裏看到

+0

源代碼鏈接已死。 –

+0

@ andrew-p鏈接已修復。 – blessenm

相關問題