【问题标题】:Set Custom Component Height/Width Programatically以编程方式设置自定义组件高度/宽度
【发布时间】:2011-12-12 15:05:34
【问题描述】:

我有一个自定义组件,我知道宽度和高度始终如下:

android:layout_width="fill_parent" 

android:layout_height="wrap_content"

我想避免在 XML 中指定宽度和高度,因为任何其他设置都是错误的。

我尝试了很多东西,但没有任何效果。例如,这段代码不起作用:

public class MyLayout extends ViewGroup {...

LayoutParams layoutParams = 
new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
setLayoutParams(layoutParams);

但无论我做什么,我都会收到异常消息“您必须提供 layout_width 属性”。如果我放回 XML layout_widthlayout_height,它就会消失。

我也尝试过覆盖onFinishInflate(),但从未被调用。我尝试从ViewViewGroupTableLayout 继承。我试过调用getLayoutParams(),但它返回null。

如何让我的自定义组件不需要在 XML 中指定这些?

请不要恶作剧。

谢谢。

【问题讨论】:

标签: android view custom-controls android-layout tablelayout


【解决方案1】:

你有答案,

LayoutParams layoutParams = new LayoutParams(width, height); setLayoutParams(layoutParams);

高度和宽度以 px、dip、sp 为单位指定

或者,其中一些提供了 setHeight 和 setWidth 方法,您可以使用它们。

【讨论】:

  • 正如我所提到的,这不起作用。它执行,但在构造后的某个时间仍然抛出相同的异常。不过还是谢谢。
  • 高度和宽度在哪一个中提供? px,倾角还是 sp?不可能同时是所有的,对吧?假设我做 new LayoutParams(10, 10),是 10 dip 吗? 10 像素? 10 sp?
猜你喜欢
  • 1970-01-01
  • 2011-06-29
  • 2012-01-23
  • 2021-08-12
  • 2011-03-09
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 2018-02-16
相关资源
最近更新 更多