Android 检测ViewTreeObserver全局布局上次调用
我已经看到了许多关于ViewTreeObserver的问题(和答案),但没有一个完全回答了我面临的问题。这就是我所拥有的: 我在scrollview中以编程方式添加了一些视图。设置完所有布局后,我想滚动到scrollview中的特定视图。为此,我使用了视图树观察者,代码如下(我正在做的一些伪代码) 注意:我之所以添加Android 检测ViewTreeObserver全局布局上次调用,android,android-layout,android-viewtreeobserver,Android,Android Layout,Android Viewtreeobserver,我已经看到了许多关于ViewTreeObserver的问题(和答案),但没有一个完全回答了我面临的问题。这就是我所拥有的: 我在scrollview中以编程方式添加了一些视图。设置完所有布局后,我想滚动到scrollview中的特定视图。为此,我使用了视图树观察者,代码如下(我正在做的一些伪代码) 注意:我之所以添加firstTime==3,是因为在这个特定的例子中,我注意到它只调用全局布局3次 因此,我的问题如下:当全局布局完成所有必要的测量时,我如何才能干净地检测到它? 是的,我有一些变通办
firstTime==3
,是因为在这个特定的例子中,我注意到它只调用全局布局3次
因此,我的问题如下:当全局布局完成所有必要的测量时,我如何才能干净地检测到它?
是的,我有一些变通办法,比如增加一个小的延迟,这将给全局布局留出时间来完成它的措施,但我正在寻找另一种(更干净的)方法来实现这一点
有什么想法吗?
谢谢
viewInsideScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public synchronized void onGlobalLayout() {
firstTime++; // Counts how many times I enter the listener
if (firstTime == 1) {
// Here the fully measure of the scroll view has not happened
} else if (firstTime == 2) {
// I still don't have the full measure of the scroll view (Let's say that, for example, paddings are missing/weren't calculated)
} else if (firstTime == 3) {
// Here is when I can safely get the locationOfTheView variable and the scroll down will happen perfectly!
viewInsideScrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
scrollView.scrollTo(0, locationOfTheView);
}
}
});