20

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?

Community
  • 1
  • 1
David
  • 307
  • 1
  • 2
  • 6

4 Answers4

15
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);
Hanish Sharma
  • 869
  • 8
  • 23
12

You need to use this:

LinearLayout.LayoutParams or RelativeLayout.LayoutParams.

xCHAN
  • 118
  • 15
Vigor
  • 1,706
  • 3
  • 26
  • 47
6

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 .

IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
0

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.

M_droid
  • 2,447
  • 2
  • 25
  • 35