Android set button margin programmatically
Asked Answered
C

5

21

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?

Claire answered 27/8, 2015 at 6:1 Comment(1)
Just add a line at last which is yourButton.setLayoutParams(params);Madancy
A
12

You need to use this:

LinearLayout.LayoutParams or RelativeLayout.LayoutParams.

Armet answered 27/8, 2015 at 6:5 Comment(0)
C
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);
Coimbatore answered 27/8, 2015 at 6:4 Comment(0)
A
12

You need to use this:

LinearLayout.LayoutParams or RelativeLayout.LayoutParams.

Armet answered 27/8, 2015 at 6:5 Comment(0)
C
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 .

Collaborationist answered 27/8, 2015 at 6:23 Comment(3)
I guess,I have posted the same answer earlier :-DCoimbatore
@HanishSharma Same logic .But not copy :PCollaborationist
Yeah i can understand :-PCoimbatore
U
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.

Ugric answered 4/5, 2022 at 12:14 Comment(0)
F
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);
Forfar answered 11/12, 2023 at 20:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.