22

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?

1
  • 1
    Just add a line at last which is yourButton.setLayoutParams(params); Commented Aug 27, 2015 at 6:04

5 Answers 5

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);
Sign up to request clarification or add additional context in comments.

Comments

12

You need to use this:

LinearLayout.LayoutParams or RelativeLayout.LayoutParams.

Comments

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 .

3 Comments

I guess,I have posted the same answer earlier :-D
@HanishSharma Same logic .But not copy :P
Yeah i can understand :-P
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.

Comments

0

For those of you looking to do this with an existing Button, and existing parameters, to get the existing parameters and change them, you typecast the LayoutParams to the type of layout that the button is inside of:

//get the current params
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) button.getLayoutParams();
//change something in the params
params.setMargins(0, 0, 0, 200);
//set the button with the new params
button.setLayoutParams(params);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.