How to set layout_margin programmatically?

Monali picture Monali · Apr 26, 2011 · Viewed 48.1k times · Source

I want to know how to set layout_marginLeft, layout_marginTop, layout_marginBottom programmatically using screen height and width. Please help me.

Thanks Monali

Answer

RoflcoptrException picture RoflcoptrException · Apr 26, 2011

Here is an example (adapted from this answer):

LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

params.setMargins(10, 20, 30, 40);

Button button = new Button(this);
button.setText("some text");
layout.addView(button, params);