android add padding between radiogroup buttons programmatically

给你一囗甜甜゛ 提交于 2019-12-09 09:27:30

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/10951848/android-add-padding-between-radiogroup-buttons-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!