View.onMeasure() 未调用
我有一个非常简单的自定义视图,并覆盖了 onMeasure()
。我的onMeasure()
根据背景Drawable决定大小。当视图第一次从 xml 创建时,一切正常。但后来我以编程方式设置了不同的背景,因此视图应该调整大小。视图现在具有不同的背景,但不会调整大小,并且不会调用 onMeasure()
。
我尝试了一切 - requestLayout()
、forceLayout()
、invalidate()
、setLayoutParams()
- 没有任何影响。我做错了什么?我只想调整我的视图大小。
I have a very simple custom View with onMeasure()
overriden. My onMeasure()
decides the size according to the background Drawable. When the View is first created from xml everything works normally. But then I set a different background programatically, so the View should resize. The View has now a different background, but it doesn't resize and onMeasure()
is not called.
I tried everything - requestLayout()
, forceLayout()
, invalidate()
, setLayoutParams()
- without any effect. What am I doing wrong? I just want my View to resize.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是我在 View 的 onSizeChanged() 中调用 setBackground() 。我重构了代码,现在可以运行了。
The problem was that I was calling setBackground() inside my View's onSizeChanged(). I refactored the code and it works now.
您是否尝试过显而易见的事情,即您的方法是如何声明的?
如果您没有添加
@override
注释,请添加它,并查看编译器是否告诉您它没有覆盖任何内容。如果是这样,请检查 的名称和方法签名onMeasure
。否则,请确保您了解何时应调用
measure()
方法:Android 如何绘制视图。Have you tried the obvious thing, i.e. how is your method declared?
If you did not add the
@override
annotation, add it, and see if your compiler tells you that it is not overriding anything. If so, check the name and method signature ofonMeasure
.Otherwise, make sure you understand when the
measure()
method is supposed to be called: How Android draws Views.