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

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中指定的这些组件?

请不要贪吃。

谢谢。

最佳答案

你有答案,

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

高度和宽度以px,dip,sp指定

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

07-24 09:48
查看更多