0

I have a ViewGroup. In this ViewGroup I would like to add three buttons that take up the whole size of the ViewGroup, each evenly taking up the same amount of space.

Where do I add these buttons? I've tried doing it in the constructor, in onDraw, in onLayout, and none of them seem to display anything.

Cœur
  • 37,241
  • 25
  • 195
  • 267
theostorm
  • 43
  • 8
  • ViewGroup has a .addView() method – NaviRamyle Oct 02 '15 at 05:06
  • Possible duplicate of http://stackoverflow.com/questions/6216547/android-dynamically-add-views-into-view – Eric B. Oct 02 '15 at 05:06
  • addView() isn't doing it unfortunately. I believe it has something to do with calling .layout on the view, inside of OnLayout, but I'm not sure how to get it to evenly space. – theostorm Oct 02 '15 at 05:12

1 Answers1

1

First you should create a button.

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);

And that's it! The most important part is setting the layout params. Remember to use the right params or an exception will be thrown.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Should the button be created in my MainActivity or inside the ViewGroup that I want it to be placed in? It seems like it is unorganized to create it in the MainActivity. – theostorm Oct 02 '15 at 05:26
  • You should use my code in an `Activity` class. I think it is not unorganized if you put it in another method for this specific purpose @theostorm – Sweeper Oct 02 '15 at 05:27
  • You can add the code in other classes too. But you need a `Context` instance to create the button. If you are creating this in a ViewGroup, there should be a getContext method there. @theostorm – Sweeper Oct 02 '15 at 05:40