2015-10-02 81 views
0

我有一個ViewGroup。在這個ViewGroup中,我想添加三個按鈕,佔據ViewGroup的整個大小,每個按鈕均勻佔用相同的空間量。Android以編程方式將按鈕添加到ViewGroup

我在哪裏添加這些按鈕?我試過在構造函數中,在onDraw中,在onLayout中,它們都沒有顯示任何東西。

+0

ViewGroup有一個.addView()方法 – NaviRamyle

+0

可能的重複http://stackoverflow.com/questions/6216547/android-dynamically-add-views-into-view –

+0

addView()不是很幸運。我相信這與在OnLayout內部的視圖上調用.layout有關,但我不知道如何將它均勻地分配給空間。 – theostorm

回答

1

首先你應該創建一個按鈕。

Button button = new Button (this); 
//And you want to set some properties of the view 
button.setLayoutParams (new RelativeLayout.LayoutParams (....));//Here you should use the corresponding layout params for different ViewGroups, here I used RelativeLayout. 
//Maybe you want to set other properties... 

ViewGroup viewGroup = //Here get your view group 
viewGroup.addView (button); 

就是這樣!最重要的部分是設置佈局參數。 請記住使用正確的參數或將拋出異常

+0

該按鈕應該在我的MainActivity中創建,還是在我希望將其放置在ViewGroup中的按鈕中創建?在MainActivity中創建它似乎是無組織的。 – theostorm

+0

你應該在'Activity'類中使用我的代碼。我認爲如果你爲了這個特定的目的把它放在另一個方法中,它並不是無組織的@theostorm – Sweeper

+0

你也可以在其他類中添加代碼。但是你需要一個'Context'實例來創建按鈕。如果你在ViewGroup中創建它,那裏應該有一個getContext方法。 @theostorm – Sweeper

相關問題