Set Margin for LinearLayout - Android User Interface

Android examples for User Interface:Layout

Description

Set Margin for LinearLayout

Demo Code

/**/* ww  w .  j  av  a 2s .c  om*/
 * (c) Winterwell Associates Ltd, used under MIT License. This file is background IP.
 */
//package com.java2s;

import android.view.View;

import android.view.ViewGroup.LayoutParams;

import android.widget.LinearLayout;

public class Main {
    /**
     * For use only with LinearLayout!
     * @param v
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    public static void setMargin(View v, int left, int top, int right,
            int bottom) {
        setMargin(v, left, top, right, bottom, true);
    }

    public static void setMargin(View v, int left, int top, int right,
            int bottom, boolean horizontalWrap) {
        LinearLayout.LayoutParams layout = (LinearLayout.LayoutParams) v
                .getLayoutParams();
        if (layout == null) {
            // create a "default" layout
            layout = new LinearLayout.LayoutParams(
                    horizontalWrap ? LayoutParams.WRAP_CONTENT
                            : LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);
        }
        layout.setMargins(left, top, right, bottom);
        v.setLayoutParams(layout);
    }
}

Related Tutorials