android set margin programmatically

Try this code:

parameter =  (RelativeLayout.LayoutParams) txtField.getLayoutParams();
parameter.setMargins(leftMargin, parameter.topMargin, parameter.rightMargin, parameter.bottomMargin); // left, top, right, bottom
txtField.setLayoutParams(parameter);

Yep,

Take for example the following method that updates the left margin of a given view:

public static void setMarginLeft(View v, int left) {
    ViewGroup.MarginLayoutParams params =   
                                (ViewGroup.MarginLayoutParams)v.getLayoutParams();
    params.setMargins(left, params.topMargin, 
                            params.rightMargin, params.bottomMargin);
}

Tags:

Android