Set margins in a LinearLayout programmatically Set margins in a LinearLayout programmatically android android

Set margins in a LinearLayout programmatically


Here is a little code to accomplish it:

LinearLayout ll = new LinearLayout(this);ll.setOrientation(LinearLayout.VERTICAL);LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(     LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);layoutParams.setMargins(30, 20, 30, 0);Button okButton=new Button(this);okButton.setText("some text");ll.addView(okButton, layoutParams);


So that works fine, but how on earth do you give the buttons margins so there is space between them?

You call setMargins() on the LinearLayout.LayoutParams object.

I tried using LinearLayout.MarginLayoutParams, but that has no weight member so it's no good.

LinearLayout.LayoutParams is a subclass of LinearLayout.MarginLayoutParams, as indicated in the documentation.

Is this impossible?

No.

it wouldn't be the first Android layout task you can only do in XML

You are welcome to supply proof of this claim.

Personally, I am unaware of anything that can only be accomplished via XML and not through Java methods in the SDK. In fact, by definition, everything has to be doable via Java (though not necessarily via SDK-reachable methods), since XML is not executable code. But, if you're aware of something, point it out, because that's a bug in the SDK that should get fixed someday.


To add margins directly to items (some items allow direct editing of margins), you can do:

LayoutParams lp = ((ViewGroup) something).getLayoutParams();if( lp instanceof MarginLayoutParams ){    ((MarginLayoutParams) lp).topMargin = ...;    ((MarginLayoutParams) lp).leftMargin = ...;    //... etc}else    Log.e("MyApp", "Attempted to set the margins on a class that doesn't support margins: "+something.getClass().getName() );

...this works without needing to know about / edit the surrounding layout. Note the "instanceof" check in case you try and run this against something that doesn't support margins.