【问题标题】:Android Resizing Radio Button programmaticallyAndroid以编程方式调整单选按钮的大小
【发布时间】:2018-11-05 19:07:31
【问题描述】:

是否可以在 Android 中以编程方式为 RadioButton 分配宽度和高度?我知道我们可以通过使用 scaleX 和 scaleY 属性来做到这一点。我正在寻找的是,如果用户在 int 中给出宽度和高度,我们如何应用到 RadioButton?

【问题讨论】:

    标签: android radio-button


    【解决方案1】:

    试试这个:

    myRadioButton.getButtonDrawable().setBounds(/* play around with the bounds */);
    

    Drawable class 上的文档说这是更改 Drawable 大小的方法。不幸的是,它的工作原理还不是很清楚,所以你需要尝试一下。

    【讨论】:

    • 我试过这个,我猜它改变了布局边界,但实际上并没有影响 RadioButton 的大小。另外我正在创建一个自定义 RadioButton,所以我试图从自定义组件本身设置它的大小
    • 您的自定义 RadioButton 扩展了什么?
    • 它从 Android 扩展 RadioButton
    • @TheWanderer...不幸的是 setBounds 也没有帮助
    • 可能是setPadding()?
    【解决方案2】:

    由于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 时,我的按钮从屏幕上消失了我以这种方式调整了它们的大小)。

    【讨论】:

    • 我同意 setScaleX 和 Y 改变大小,我正在寻找的解决方案是当用户在 int 中指定高度和宽度时,我如何在设置大小时映射它?
    • 好的,我想我更能理解你的问题:只使用整数输入,你想设置按钮的大小及其内容,对吧?我已按答案进行编辑以解决此问题。
    • 是的,你问我的问题是对的。我会尝试解决方案并让您知道。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2020-01-31
    • 2012-02-06
    • 2017-07-20
    • 2018-07-13
    • 2011-07-08
    相关资源
    最近更新 更多