如何为Android中的按钮指定宽度和高度?
我正在开发一个小型 Android 应用程序,其中包含一些从 Java 代码动态创建的方形按钮。我使用 Absolute.LayoutParams 方法为它们提供宽度和高度,但我收到弃用警告。
LayoutParams params = new LayoutParams(width,height, 0, 0);
button.setLayoutParams(params);
我也尝试过:
button.setHeight(height);
button.setWidth(width);
但它不起作用。还有第三种方法可以轻松清洁吗?
先感谢您!
I'm developing a little Android app with some square buttons created dynamically from Java code. I'm using the Absolute.LayoutParams method to give width and height to them, but I get deprecation warnings.
LayoutParams params = new LayoutParams(width,height, 0, 0);
button.setLayoutParams(params);
I tried this too:
button.setHeight(height);
button.setWidth(width);
But it is not working. There is a third way to do it easily and clean?
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想会是
i think it will be
使用
AbsoluteLayout
,您需要使用AbsoluteLayout.LayoutParams
,而不是ViewGroup.LayoutParams
。另请注意,设置
View
宽度和高度的正确方法是通过LayoutParams
进行设置。请参阅ViewGroup.LayoutParams
和View.getLayoutParams()
。您不必像第二个示例中那样手动设置宽度和高度。不过,我强烈建议您使用
RelativeLayout
(或LinearLayout
等)来实现此功能...AbsoluteLayout
已弃用,并且有充分的理由。现在有很多不同的 Android 设备具有不同尺寸的屏幕,AbsoluteLayout
无法在所有设备上工作。永远、永远、永远使用AbsoluteLayout
总是好的做法:)。Using an
AbsoluteLayout
, you need to useAbsoluteLayout.LayoutParams
, rather thanViewGroup.LayoutParams
.Also note that the proper way to set the width and height of a
View
is to do so via theLayoutParams
. SeeViewGroup.LayoutParams
andView.getLayoutParams()
. You shouldn't have to set the width and height manually as you do in your second example.I strongly suggest, however, that you implement this with a
RelativeLayout
(orLinearLayout
, etc.) instead...AbsoluteLayout
is deprecated, and for very good reason. There are so many different Android devices with different sized screens now,AbsoluteLayout
just won't work across them all. Never, ever, ever usingAbsoluteLayout
is always good practice :).