片段:测量视图的最佳位置是什么?

时间:2013-06-05 09:38:24

标签: android android-layout android-fragments android-view android-lifecycle

我有一个片段,我需要在屏幕上测量其视图的位置/宽度/高度,并传递给其他类。

所以我所拥有的是一个能够实现它的功能,如下所示:

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! IMO。

有更好的方法吗?看起来像是一件基本的事情

2 个答案:

答案 0 :(得分:6)

在您的片段的onActivityCreated内检索currentView(带有getView())并将runnable发布到其队列中。在runnable调用measureTest()

答案 1 :(得分:1)

没有更好的方法。那段代码并不坏!一旦视图布局(我的术语可能有点奇怪)就会在测量后立即触发。这就是Google的Android文档中BitmapFun sample(参见ImageGridFragment,第120行)的方法。对该特定代码段的评论如下:

 // This listener is used to get the final width of the GridView and then calculate the
 // number of columns and the width of each column. The width of each column is variable
 // as the GridView has stretchMode=columnWidth. The column width is used to set the height
 // of each view so we get nice square thumbnails.
相关问题