我有一個ViewGroup。在這個ViewGroup中,我想添加三個按鈕,佔據ViewGroup的整個大小,每個按鈕均勻佔用相同的空間量。Android以編程方式將按鈕添加到ViewGroup
我在哪裏添加這些按鈕?我試過在構造函數中,在onDraw中,在onLayout中,它們都沒有顯示任何東西。
我有一個ViewGroup。在這個ViewGroup中,我想添加三個按鈕,佔據ViewGroup的整個大小,每個按鈕均勻佔用相同的空間量。Android以編程方式將按鈕添加到ViewGroup
我在哪裏添加這些按鈕?我試過在構造函數中,在onDraw中,在onLayout中,它們都沒有顯示任何東西。
首先你應該創建一個按鈕。
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);
就是這樣!最重要的部分是設置佈局參數。 請記住使用正確的參數或將拋出異常。
ViewGroup有一個.addView()方法 – NaviRamyle
可能的重複http://stackoverflow.com/questions/6216547/android-dynamically-add-views-into-view –
addView()不是很幸運。我相信這與在OnLayout內部的視圖上調用.layout有關,但我不知道如何將它均勻地分配給空間。 – theostorm