簡體   English   中英

Android以編程方式調整單選按鈕的大小

[英]Android Resizing Radio Button programmatically

是否可以通過編程為Android中的RadioButton分配寬度和高度? 我知道我們可以通過使用scaleX和scaleY屬性來做到這一點。 我要尋找的是,如果用戶以int給出寬度和高度,我們如何將其應用於RadioButton?

嘗試這個:

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

Drawable類的文檔說這是您更改Drawable大小的方法。 不幸的是,尚不清楚它是如何工作的,因此您需要嘗試一下。

由於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時,我調整按鈕大小時會在屏幕上放血這條路)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM