3

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

所以我所拥有的是一个功能,它是这样的:

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!国际海事组织。

有没有更好的方法来做到这一点?似乎是一件很基本的事情

4

2 回答 2

6

onActivityCreated您的片段内部检索 currentView (使用getView())并将可运行的内容发布到其队列中。在可运行调用内部measureTest()

于 2013-06-05T09:41:12.047 回答
1

没有更好的办法。那个代码还不错!一旦视图布局好(我的术语可能有点奇怪),它就会在测量后立即触发。Google 的 Android 文档中的BitmapFun 示例(参见 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.
于 2013-06-05T09:47:37.893 回答