Set margins in a LinearLayout programmatically.

Posted by Timmmm on Stack Overflow See other posts from Stack Overflow or by Timmmm
Published on 2010-03-20T01:04:47Z Indexed on 2010/03/20 1:11 UTC
Read the original article Hit count: 689

Filed under:
|
|
|
|

I'm trying to use Java (not XML) to create a LinearLayout with buttons that fill the screen, and have margins. Here is code that works without margins:

  LinearLayout buttonsView = new LinearLayout(this);
  buttonsView.setOrientation(LinearLayout.VERTICAL);
  for (int r = 0; r < 6; ++r)
  {
   Button btn = new Button(this);
   btn.setText("A");

   LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); // Verbose!
   lp.weight = 1.0f; // This is critical. Doesn't work without it.
   buttonsView.addView(btn, lp);
  }
  ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
  setContentView(buttonsView, lp);

So that works fine, but how on earth do you give the buttons margins so there is space between them? I tried using LinearLayout.MarginLayoutParams, but that has no weight member so it's no good. And it doesn't work if you pass it lp in its constructor either.

Is this impossible? Because it sure looks it, and it wouldn't be the first Android layout task you can only do in XML.

© Stack Overflow or respective owner

Related posts about android

Related posts about view