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

13
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
  • 849
  • 8
  • 22
12

You need to use this:

LinearLayout.LayoutParams or RelativeLayout.LayoutParams.

xCHAN
  • 118
  • 13
Vigor
  • 1,592
  • 2
  • 24
  • 42
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
  • 73,189
  • 14
  • 161
  • 193
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
  • 1,740
  • 2
  • 19
  • 30