'Android set button margin programmatically

I know this question has been asked before, like this:

similar questions

But my issue is when I do this:

LayoutParams params = new LayoutParams(
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);

It shows there's no setMargins for params. Who can help?



Solution 1:[1]

LayoutParams params = new LayoutParams(
            LayoutParams.WRAP_CONTENT,      
            LayoutParams.WRAP_CONTENT
    );
params.setMargins(left, top, right, bottom);

You are missing this line i guess

button.setLayoutParams(params);

Solution 2:[2]

You are missing setLayoutParams(params) Attribute

    LayoutParams params = new LayoutParams(
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
Your_Layout.setLayoutParams(params);

I hope it will helps you .

Solution 3:[3]

For Kotlin do this:

val btn = Button(requireContext())
val lParams = LinearLayout.LayoutParams(
              LinearLayout.LayoutParams.MATCH_PARENT,
              LinearLayout.LayoutParams.WRAP_CONTENT
         )
val marginInDp = 5.toPx() // 5dp
lParams.setMargins(marginInDp,marginInDp,marginInDp,marginInDp)

Watch for the size when setting margins. First I set 5 (px) and wondered why it's not working. Came out it was too little.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hanish Sharma
Solution 2
Solution 3 M_droid