我有一个片段,我需要在屏幕上测量其视图的位置/宽度/高度并传递给其他类。
所以我所拥有的是一个功能,它是这样的:
private void measureTest(){
v = ourView.findViewById(R.id.someTextField);
v.getLocationOnScreen(loc);
int w = v.getWidth();
...
SomeClass.passLocation(loc,w);
...
问题是视图的位置/宽度/高度在片段生命周期内还没有准备好。因此,如果我在这些生命周期方法中运行该函数:
onCreateView
onViewCreated
onStart
onResume
我要么得到错误的位置和宽度/高度测量值,要么得到 0 值。我找到的唯一解决方案是将GlobalLayoutListener
这样的添加到 mainView
mainView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
if(alreadyMeasured)
mainView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
else
measureTest();
}
});
这完成了工作.. 但它只是 Yack!国际海事组织。
有没有更好的方法来做到这一点?似乎是一件很基本的事情