【发布时间】:2018-11-05 19:07:31
【问题描述】:
是否可以在 Android 中以编程方式为 RadioButton 分配宽度和高度?我知道我们可以通过使用 scaleX 和 scaleY 属性来做到这一点。我正在寻找的是,如果用户在 int 中给出宽度和高度,我们如何应用到 RadioButton?
【问题讨论】:
标签: android radio-button
是否可以在 Android 中以编程方式为 RadioButton 分配宽度和高度?我知道我们可以通过使用 scaleX 和 scaleY 属性来做到这一点。我正在寻找的是,如果用户在 int 中给出宽度和高度,我们如何应用到 RadioButton?
【问题讨论】:
标签: android radio-button
试试这个:
myRadioButton.getButtonDrawable().setBounds(/* play around with the bounds */);
Drawable class 上的文档说这是更改 Drawable 大小的方法。不幸的是,它的工作原理还不是很清楚,所以你需要尝试一下。
【讨论】:
setPadding()?
由于RadioButton继承自TextView,你可以使用myRadioButton.setHeight(int pixels)和.setWidth(int pixels)来设置整个按钮区域的大小,但不能设置文字和选择圈。要更改内容的大小而不是整体区域,您可以使用.setScaleX(float scale) 和.setScaleY() 您将更改文本和选择圆圈,但不能更改按钮区域。
因此要同时更改按钮区域及其内容的大小:
int desiredWidth = 500; // Set to your desired width.
int currentWidth = radioButton.getWidth();
radioButton.setScaleX(desiredWidth / currentWidth);
radioButton.setWidth(desiredWidth);
高度也是如此。
如果要保持纵横比,只需设置所需的宽度,然后:
desired_height = desired_width * current_height / current_width
像这样:
int desiredWidth = 500;
int currentHeight = radioButton.getHeight();
int currentWidth = radioButton.getWidth();
int desiredHeight = desiredWidth * currentHeight / currentWidth;
radioButton.setScaleY(desiredHeight / currentHeight);
radioButton.setHeight(desiredHeight);
radioButton.setScaleX(desiredWidth / currentWidth);
radioButton.setWidth(desiredWidth);
似乎从中心调整了比例,没有调整位置,因此您可能必须更改位置(如果您使用 ConstraintLayout,这可能没有实际意义——使用 LinearLayout 时,我的按钮从屏幕上消失了我以这种方式调整了它们的大小)。
【讨论】: