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);
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);