簡體   English   中英

如何在Android中為按鈕提供寬度和高度?

[英]How to give width and height to a button in Android?

我正在開發一個小的Android應用程序,其中包含一些從Java代碼動態創建的方形按鈕。 我正在使用Absolute.LayoutParams方法為它們提供寬度和高度,但是我收到了棄用警告。

LayoutParams params = new LayoutParams(width,height, 0, 0);
button.setLayoutParams(params);

我也嘗試過這個:

button.setHeight(height);
button.setWidth(width);

但這是行不通的。 還有第三種方法可以輕松清潔它嗎?

先感謝您!

我認為這將是

LayoutParams params = new LayoutParams(width,height);
button.setLayoutParams(params);

使用AbsoluteLayout ,您需要使用AbsoluteLayout.LayoutParams ,而不是ViewGroup.LayoutParams

AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(width, height, 0, 0);
button.setLayoutParams(params);

還要注意,設置View的寬度和高度的正確方法是通過LayoutParams 請參見ViewGroup.LayoutParamsView.getLayoutParams() 您不必像第二個示例中那樣手動設置寬度和高度。

但是,我強烈建議您改為使用RelativeLayout (或LinearLayout等)來實現此目的…… AbsoluteLayout已過時,這是有充分理由的。 現在有許多不同尺寸屏幕的Android設備, AbsoluteLayout不能在所有設備上同時使用。 永遠不要使用AbsoluteLayout永遠是一個好習慣:)。

暫無
暫無

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

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