android add padding between radiogroup buttons programmatically
Asked Answered
B

1

14

I have a radiogroup in xml, and the buttons are generated programmatically. How do I add spacing between the buttons programmatically.

I thought it was something like LayoutParams but my object doesn't come with an obvious setPadding or setMargins method.

This is what I was trying

RadioButton currentButton = new RadioButton(context);
            currentButton.setText(item.getLabel());
            currentButton.setTextColor(Color.BLACK);

            //add padding between buttons
            LayoutParams params = new LayoutParams(context, null);
            params. ... ??????
            currentButton.setLayoutParams(params);
Boscage answered 8/6, 2012 at 15:34 Comment(0)
B
27

Padding

Normal LayoutParams don't have methods to apply padding, but views do. Since a RadioButton is a subclass of view, you can use View.setPadding(), for example like this:

currentButton.setPadding(0, 10, 0, 10);

This adds 10px padding at the top and 10px at the bottom. If you want to use other units beside px (e.g. dp) you can use TypedValue.applyDimension() to convert them to pixels first.

Margins

Margins are applied to some specific LayoutParams classes which subclass MarginLayoutParams. Make sure to use a specific subclass when setting a margin, e.g. RadioGroup.LayoutParams instead of the generic ViewGroup.LayoutParams (when your parent layout is a RadioGroup). Then you can simply use MarginLayoutParams.setMargins().

Sample:

RadioGroup.LayoutParams params 
           = new RadioGroup.LayoutParams(context, null);
params.setMargins(10, 0, 10, 0);
currentButton.setLayoutParams(params);
Benjamin answered 8/6, 2012 at 15:38 Comment(2)
Hi. I tried the margins code above and it doesn't work. The buttons are simple on beside another.Chroma
I think the default padding value is approximately 10, so when you give 10 padding you will not notice it, try some bigger value like 40 and you will see it working.Israelite

© 2022 - 2024 — McMap. All rights reserved.