Change margin of a view programmatically?

Let suppose view in a LinearLayout. First you have to get Layoutparams of the view and cast into to specific Layoutparams and modify the margins. As I remove margins by setting it all by 0.

((LinearLayout.LayoutParams) view.getLayoutParams()).setMargins(0,0,0,0);

               {or}

((LinearLayout.LayoutParams) view.getLayoutParams()).topMargin = 5;

OR

You can create a LayoutParams variable and set margins to it. And set LayoutParams back to the view. as below

LinearLayout.LayoutParams parmas = (LinearLayout.LayoutParams) holder.imageView.getLayoutParams();
            parmas.setMargins(0,5,0,0);
            holder.imageView.setLayoutParams(parmas);

OR

You can use it in more generic way without specifying the particular Layout.


If the view is inside RelativeLayout.

RelativeLayout.LayoutParmas

Or you can use generic ViewGroup.MarginLayoutParams without specifying parent

if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams mp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        mp.setMargins(0,5,0,0);
        view.requestLayout();
    }

Leave a Reply

Your email address will not be published. Required fields are marked *