Android以编程方式在radiogroup按钮之间添加填充 [英] android add padding between radiogroup buttons programmatically
问题描述
我在xml中有一个广播组,并且按钮是通过编程生成的.如何以编程方式在按钮之间添加间距.
I have a radiogroup in xml, and the buttons are generated programmatically. How do I add spacing between the buttons programmatically.
我认为它类似于LayoutParams
,但是我的对象没有明显的setPadding
或setMargins
方法.
I thought it was something like LayoutParams
but my object doesn't come with an obvious setPadding
or setMargins
method.
这就是我正在尝试的
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);
推荐答案
填充
普通LayoutParams
没有应用填充的方法,但是视图却有.由于RadioButton是视图的子类,因此可以使用
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);
这将在顶部添加10px填充,在底部添加10px.如果要使用px (例如dp
)之外的其他单位,则可以使用
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.
保证金
边距应用于某些特定的LayoutParams类,这些类子类 MarginLayoutParams .设置边距时,请确保使用特定的子类,例如RadioGroup.LayoutParams
而不是通用的ViewGroup.LayoutParams (当您的父布局是RadioGroup
时).然后,您可以简单地使用
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()
.
示例:
RadioGroup.LayoutParams params
= new RadioGroup.LayoutParams(context, null);
params.setMargins(10, 0, 10, 0);
currentButton.setLayoutParams(params);
这篇关于Android以编程方式在radiogroup按钮之间添加填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!