以编程方式设置自定义组件高度/宽度
我有一个自定义组件,我知道宽度和高度始终如下:
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_width
、layout_height
,该问题就会消失。
我还尝试过重写 onFinishInflate() ,但从未被调用。我尝试从 View
、ViewGroup
和 TableLayout
继承。我尝试调用 getLayoutParams()
,但它返回 null。
如何让我的自定义组件不需要在 XML 中指定这些内容?
请不要尖刻。
谢谢。
I have a custom component where I know the width and height is always as follows:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
I would like to avoid having to specify the width and height in XML since any other settings are wrong.
I've tried a lot of things, but nothing works. For example, this code doesn't work:
public class MyLayout extends ViewGroup {...
LayoutParams layoutParams =
new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
setLayoutParams(layoutParams);
but no matter what I do, I get the exception message "You must supply a layout_width attribute." which goes away if I put back the XML layout_width
, layout_height
.
I've also tried to Override onFinishInflate()
, but that never gets called. I tried inheriting from View
, ViewGroup
and TableLayout
. I've tried calling getLayoutParams()
, but it returns null.
How do I get my custom component to not need these specified in XML?
Please no snark.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你已经有了答案,
LayoutParamslayoutParams = new LayoutParams(width, height);
setLayoutParams(layoutParams);
高度和宽度以 px、dip、sp 指定。
另外,有些提供了 setHeight 和 setWidth 方法,您可以使用它们。
You have the answer,
LayoutParams layoutParams = new LayoutParams(width, height);
setLayoutParams(layoutParams);
height and width are specified in px, dip, sp
Alternatively, some of them provide with setHeight and setWidth methods, you can use them.