在一个片段中,我使用多个子视图来扩展布局。我需要获取其中之一的尺寸(宽度和高度),这是一个自定义视图。
在自定义视图类中,我可以很容易地做到这一点。但是如果我尝试从片段开始,我总是得到0作为维度。
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
View culoide = view.findViewWithTag(DRAW_AREA_TAG);
Log.d("event", "culoide is: "+culoide.getWidth()); // always 0
}
我认为onViewCreated应该是获得它的正确地方,但这种情况确实发生了。我在super.onViewCreated之前尝试过,在debug中看起来'findViewWithTag‘找到了正确的视图,只尝试了API7 v4支持。
有什么帮助吗?
发布于 2013-06-05 03:03:17
必须等到第一次测量和布局之后,才能获得getWidth()
和getHeight()
的非零值。您可以使用ViewTreeObserver.OnGlobalLayouListener
来实现这一点
public void onViewCreated(final View view, Bundle saved) {
super.onViewCreated(view, saved);
view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
// get width and height of the view
}
});
}
发布于 2014-01-02 17:33:56
我的首选方法是将一个OnLayoutChangeListener
添加到要跟踪其自身的视图中
CustomView customView = ...
customView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
// Make changes
}
});
如果只想要初始布局,可以在回调中移除监听器。
发布于 2019-08-14 23:17:20
使用ViewTreeObserver.OnGlobalLayoutListener
、View.post(Runnable action)
或onWindowFocusChanged()
不是最好的解决方案。这篇article (注意:我是本文的作者)解释了其中的原因,并使用基于View.OnLayoutChangeListener
的doOnLayout
kotlin扩展提供了一个有效的解决方案。如果你想在Java语言中使用它,在文章中有一个指向doOnLayout
源代码的链接,它非常简单,你也可以在Java语言中做类似的事情。
https://stackoverflow.com/questions/16925317
复制相似问题