【问题标题】:How to give width and height to a button in Android?如何为Android中的按钮指定宽度和高度?
【发布时间】:2012-01-19 09:49:56
【问题描述】:

我正在开发一个带有一些方形按钮的小型 Android 应用程序,这些按钮是从 Java 代码动态创建的。我正在使用 Absolute.LayoutParams 方法为它们提供宽度和高度,但我收到了弃用警告。

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

我也试过这个:

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

但它不起作用。还有第三种方法可以轻松清洁?

提前谢谢你!

【问题讨论】:

    标签: android button height width


    【解决方案1】:

    我认为会是

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 如果您的视图布局是固定的,那么使用 XML 完成所有这些操作可能也是一个更好的主意。您的代码会看起来更漂亮(如果必须,以后进行更改会更容易)。
      猜你喜欢
      • 2013-11-29
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多