如何为Android中的按钮指定宽度和高度?

发布于 2024-12-27 16:08:21 字数 357 浏览 0 评论 0原文

我正在开发一个小型 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吹泡泡o 2025-01-03 16:08:21

我想会是

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

i think it will be

LayoutParams params = new LayoutParams(width,height);
button.setLayoutParams(params);
開玄 2025-01-03 16:08:21

使用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 总是好的做法:)。

Using an AbsoluteLayout, you need to use AbsoluteLayout.LayoutParams, rather than ViewGroup.LayoutParams.

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

Also note that the proper way to set the width and height of a View is to do so via the LayoutParams. See ViewGroup.LayoutParams and View.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 (or LinearLayout, 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 using AbsoluteLayout is always good practice :).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文