【发布时间】:2013-06-05 09:38:23
【问题描述】:
我有一个片段,我需要在屏幕上测量其视图的位置/宽度/高度并传递给其他类。
所以我有一个功能,它是这样的:
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!国际海事组织。
有没有更好的方法来做到这一点?似乎是一件很基本的事情
【问题讨论】:
标签: android android-layout android-fragments android-view android-lifecycle