android add padding between radiogroup buttons programmatically

后端 未结 1 1089
轻奢々
轻奢々 2021-02-13 15:00

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

相关标签:
1条回答
  • 2021-02-13 15:36

    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);
    
    0 讨论(0)
提交回复
热议问题