【问题标题】:Fragments : what is the best place to measure Views?片段:衡量观看次数的最佳地点是什么?
【发布时间】: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


    【解决方案1】:

    在片段的onActivityCreated 内检索当前视图(使用getView())并将一个可运行对象发布到其队列中。在可运行的调用内部measureTest()

    【讨论】:

      【解决方案2】:

      没有更好的方法。那个代码还不错!一旦视图被布置(我的术语可能有点奇怪),它就会在测量之后立即触发。这就是在 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.
      

      【讨论】:

      • 感谢您的信息。我同意它并没有那么糟糕......只是整个样板代码和它的可读性有点令人沮丧。另见黑带答案
      • 调用 onActivityCreated 时,Android 系统的布局/测量通道仍在主 UI 线程的队列中。向该队列发布一个新的可运行文件可能有效,但我不能 100% 确定该队列是否总是 FIFO。也许黑带对这个话题了解得更多。我个人更喜欢使用 safter 选项,即使这意味着多几行代码:)
      • 我在使用黑带解决方案时遇到了几次与此相关的崩溃。根据我的分析,我得出了相同的结论,即在某些设备上,只有侦听器方法才能提供所需的保证。
      猜你喜欢
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      相关资源
      最近更新 更多