Android以编程方式添加按钮到ViewGroup



我有一个ViewGroup。在这个ViewGroup中,我想添加三个按钮,它们占用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);

就是这样!最重要的部分是设置布局参数。请记住使用正确的参数,否则将抛出异常

最新更新