【问题标题】:android add padding between radiogroup buttons programmaticallyandroid以编程方式在radiogroup按钮之间添加填充
【发布时间】:2012-06-12 16:33:53
【问题描述】:

我在 xml 中有一个单选组,并且按钮是通过编程方式生成的。如何以编程方式在按钮之间添加间距。

我认为它类似于LayoutParams,但我的对象没有明显的setPaddingsetMargins 方法。

这就是我正在尝试的

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

【问题讨论】:

    标签: android radio-button padding margin radio-group


    【解决方案1】:

    填充

    普通LayoutParams 没有应用填充的方法,但视图有。由于 RadioButton 是视图的子类,您可以使用View.setPadding(),例如这样:

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

    这会在顶部添加 10 像素的内边距,在底部添加 10 像素的内边距。如果您想使用 px 之外的其他单位(例如dp,您可以先使用TypedValue.applyDimension() 将它们转换为像素。

    边距

    边距应用于某些特定的 LayoutParams 类,这些类是 MarginLayoutParams 的子类。确保在设置边距时使用特定的子类,例如RadioGroup.LayoutParams 而不是通用的 ViewGroup.LayoutParams (当您的父布局是 RadioGroup 时)。然后你可以简单地使用MarginLayoutParams.setMargins()

    示例:

    RadioGroup.LayoutParams params 
               = new RadioGroup.LayoutParams(context, null);
    params.setMargins(10, 0, 10, 0);
    currentButton.setLayoutParams(params);
    

    【讨论】:

    • 嗨。我尝试了上面的边距代码,但它不起作用。旁边的按钮很简单。
    • 我认为默认的填充值大约是 10,所以当你给 10 填充时你不会注意到它,尝试一些更大的值,比如 40,你会看到它工作。
    猜你喜欢
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多