我有一个 fragment ,我需要测量它在屏幕上的 View 的位置/宽度/高度并传递给其他一些类。
所以我有一个函数可以做到这一点,就像这样:
private void measureTest(){
v = ourView.findViewById(R.id.someTextField);
v.getLocationOnScreen(loc);
int w = v.getWidth();
...
SomeClass.passLocation(loc,w);
...
问题是 View 的位置/宽度/高度在 fragment 生命周期内没有准备好。 因此,如果我在这些生命周期方法中运行该函数:
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!海事组织。
有更好的方法吗?似乎是一件很基本的事情
最佳答案
在 fragment 的 onActivityCreated
中检索 currentView(使用 getView()
)并将一个可运行对象发布到其队列中。在 runnable 内部调用 measureTest()
关于android - fragment : what is the best place to measure Views?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16936494/